Date.parse() Polyfill

In this example below you will see how to do a Date.parse() Polyfill with some HTML / CSS and Javascript

Because Date.parse() doesn't work well cross-browser with this format: MM/DD/YYYYAs a bonus, I've accounted for timezones/daylight savings.

Thumbnail
This awesome code was written by Adam, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright Adam ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Date.parse() Polyfill</title>
  
  
  
  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

</head>

<body>

  <h1>Date.parse() Polyfill<h1>
<h2>Because Date.parse() doesn't work well cross-browser with this format "MM/DD/YYYY"</h2>
<p>As a bonus, I've accounted for timezones/daylight savings.</p>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/depthdev/dateparse-polyfill-XJObmw */
var printDate = function(ms) {
  var nd = new Date(ms);
  var y = nd.getFullYear();
  var m = nd.getMonth() + 1;
  var d = nd.getDate();
  return (m < 10 ? '0' + m : m) + '/' + (d < 10 ? '0' + d : d) + '/' + y;
};
var getWeeks = function(start) {
	var weeks = {prev:{},curr:{},next:{}};
	var d = new Date(start);
	var dayOfWeek = d.getDay();
	var sunMs = start + d.getTimezoneOffset() * 60000 - (dayOfWeek * 86400000);
	weeks.prev.start = printDate(sunMs-604800000);
	weeks.prev.end = printDate(sunMs-86400000);
	weeks.curr.start = printDate(sunMs);
	weeks.curr.end = printDate(sunMs+518400000);
	weeks.next.start = printDate(sunMs+604800000);
	weeks.next.end = printDate(sunMs+1123200000);
	return weeks;
};
var parseDate = function(str) {
  if (str) {
    var str = str.replace(/[^\d\/]*/g,''); // Replace hidden characters if any
    var y = parseInt(str.replace(/.+\/.+\//,''));
    var m = parseInt(str.replace(/(.+)\/.+\/.+/,'$1')) - 1;
    var d = parseInt(str.replace(/.+\/(.+)\/.+/,'$1'));
    return new Date(y,m,d).getTime();
  } else {
    var nd = new Date();
    return new Date(nd.getFullYear(),nd.getMonth(),nd.getDate()).getTime();
  }
};
console.log(getWeeks(parseDate('11/01/2015')));
console.log(getWeeks(parseDate()));

Comments