redefine Date() javascript

83 Views Asked by At

The official calendar of our country is jalali! Jalali is a type of calendar that has a mathematical relationship with the Gregorian calendar. I want to change Date() in JS to returns jalali values. there are many lib or func for this, but I don't want use them. Can I redefine Date()? Where can I view Date() source?

2

There are 2 best solutions below

3
Jesper On

You can use toLocaleDateString();

let today = new Date().toLocaleDateString('fa-IR');
console.log(today);

fa-IR is for Farsi-Iran, but all the ISO country codes can be found here

also you can set options as second argument, for example:

let options = { year: 'numeric', month: 'long', day: 'numeric' };
new Date().toLocaleDateString('fa-IR', options);
0
RobG On

Don't mess with objects you don't own. You can create your own date object called maybe jDate (after "jalali date", which I assume is the same as the Intl object's "persian" calendar) and implement methods there.

The Intl.DateTimeFormat constructor returns an object that has a formatToParts method that you can leverage to implement the Date methods you need, then you can work on a standard Date object underneath but return Jalali values from the methods. e.g. to get all the current date parts in English:

let f = new Intl.DateTimeFormat('en-GB-u-ca-persian',{
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  weekday: 'long',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  hour12: false,
});
console.log('Current Jalali date: ' + f.format(new Date()));

console.log('The parts:');  
f.formatToParts(new Date()).forEach(part => console.log(part.type + ': ' + part.value));

For some things you have to run the format method more than once with different options, e.g. to get both the month name and number as both are specified by the month option: month: 'long' for the name and month: 'numeric' for the number.