Skip to content

Instantly share code, notes, and snippets.

@ViktorovEugene
Last active March 22, 2016 13:23
Show Gist options
  • Save ViktorovEugene/9584b96a97831c3c460f to your computer and use it in GitHub Desktop.
Save ViktorovEugene/9584b96a97831c3c460f to your computer and use it in GitHub Desktop.
JS - get the day's number since the 0001-01-01 and conversely - get the date object by the day's number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Date</title>
</head>
<body>
<script>
console.log('\nFrom date to ordinal:\n');
console.log(toordinal(new Date('1970-01-01')));
console.log(toordinal(new Date('0001-01-01')));
console.log(toordinal(new Date('0001-01-02')));
console.log(toordinal(new Date()));
console.log('\nTo date from ordinal:\n');
console.log(fromordinal(1));
console.log(fromordinal(719163));
console.log(fromordinal(736045));
function convertMilliSecondsToHours(value) {
return Math.floor(value / ( 24 * 60 * 60 * 1000 ));
}
function toMilliSeconds(value) {
return value * ( 24 * 60 * 60 * 1000 )
}
function toordinal(date) {
/* This is the js implementation of the python's
``datetime.date.toordinal()`` method.
It return the days number since the 0001-01-01
(it counts as the first day).
For example for the ``new Date('0001-01-01')`` it will be ``1``;
*/
var zeroDate = new Date('0000-12-31'),
zeroDays = Math.abs(
convertMilliSecondsToHours(zeroDate.getTime())
);
return zeroDays +
convertMilliSecondsToHours(date.getTime());
}
function fromordinal(daysNumber) {
/* This is the JS implementation of the python's
* ``datetime.date.fromordinal()`` method.
* It returns the date object gotten from the day's number
* if we take the first day as the 1 January of the 0001 year.
*/
var zeroMilliSecond = new Date('0000-12-31');
zeroMilliSecond.setHours(0);
zeroMilliSecond = zeroMilliSecond.getTime();
return new Date(toMilliSeconds(daysNumber) + zeroMilliSecond);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment