redefine Date() javascript - javascript

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?

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);

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.

Related

Get milliseconds for custom date in custom timezone

I have a date server api that works in Europe/Moscow timezone. The selected date must be sent from the client as a timestamp for the Europe/Moscow timezone.
A client from Canada choosing a date in the calendar, say November 8, 2011 has to send the timestamp in the Europe/Moscow timezone.
I can solve this problem through moment.js, but unfortunately, for certain reasons I can't use third-party libraries in the project.
Basically I need a function that does the same thing as the moment.tz method:
moment.tz('2021-11-08T00:00:00', 'Europe/Moscow');
You can use Intl.DateTimeFormat with suitable options to get a timestamp for any IANA location. The formatToParts method gets the required values, then it's just a matter of formatting them. E.g.
function toLocTimestamp(loc, date = new Date()) {
let {year, month, day, hour, minute, second, timeZoneName} = new Intl.DateTimeFormat('en', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
timeZone: loc,
timeZoneName: 'short'
}).formatToParts().reduce((parts, part) => {
parts[part.type] = part.value;
return parts;
}, Object.create(null));
// Check if timezone not offset and fix
if (!/\d/.test(timeZoneName)) {
timeZoneName = date.toLocaleString('fr',{
hour: 'numeric',
timeZone: loc,
timeZoneName: 'short'
}).match(/\S+$/)[0];
}
// Change timeZoneName to offset
let sign = timeZoneName.substring(3,4);
let offset = timeZoneName.substring(4);
let [offH, offM] = offset.split(':');
// Return timestamp
return `${year}-${month}-${day}T${hour}:${minute}:${second}${sign}${offH.padStart(2,'0')}:${offM || '00'}`;
}
// E.g.
['Europe/Moscow', 'Asia/Kolkata','Australia/Lord_Howe',
'America/St_Johns'].forEach(
loc => console.log(`${loc.padEnd(20,' ')}: ${toLocTimestamp(loc)}`)
);
The timeZoneName fix is required as depending on the language passed to dateTimeFormat and host system language, the offset might be GMT±H[:mm], UTC±H[:mm] or an abbreviation like "ChST" or "CET". If en returns an abbreviation, fr shouldn't.
This will observe DST for various locations. If a fixed offset is required, just adjust the UTC time by the offset, use toISOString to get the timestamp and remove the trailing Z.

How to format the date to (dd/mm/yyyy hh:mm:ss)

How can I convert the date below into this template (dd/mm/yyyy hh:mm:ss) ?
05/04/2021 14:52
I tried to do it that way, but I only get the time and not the date with time.
var data = new Date('05/04/2021 14:52');
var time = data.toLocaleTimeString('pt-PT', {hour12: false});
console.log(time);
You can use below script
var data = new Date('05/04/2021 14:52');
console.log(data.toLocaleString('en-GB',{hour12: false}));
Output : "04/05/2021, 14:52:00"
If you need more date-related staff than simple date formatting, you can use Moment.js.
moment().format('MMMM Do yyyy, h:mm:ss a'); // April 5th 2021, 9:16:13 pm
moment().format('DD/MM/yyyy hh:mm'); // 05/04/2021 21:18
If you need to format your date object, simply use:
moment(date).format('DD/MM/yyyy hh:mm');
Moment.js is also useful for operation on dates like days, week, month adding/subtracting, getting the start of a week, month, quarter, and many other useful operations.
This is my solution. If you want to create a advanced format, you can read more about object Intl
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
const formatDate = new Intl.DateTimeFormat("en" , {
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false
});
console.log(formatDate.format(new Date('05/04/2021 14:52')))

convert string date and time to utc based on timezone using moment

am using moment in nodejs server to convert local time from frontend to utc.
my time format is date = '10-07-2020 08:45 PM' in string format. When i use moment(date).format() its converting format to this 2020-10-07 20:45:00+05:30 timezone is adding based on server and i have timezone = '+4:00' this is my local timezone. I would like to convert my date string to UTC based on the timezone field not based on the server timezone. How can I do this?
I tried the following methods but am not getting a proper solution
moment.utc(moment(date).utcOffset(timezone)).format('YYYY-MM-DD HH:mm:ss')
Anyone Please suggest
You can use moment-timezone to create a date from a string and a certain timezone. In order to do that you need to specify your format and the corresponding timezone. Something like this:
const date = moment.tz("10-07-2020 08:45 pm", "M-D-YYYY hh:mm a", "Europe/Samara");
console.log(date.toISOString());
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>
Instead of moment, perhaps use intl DateTimeFormat?
Here are some possibilities
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', };
const date = new Date('10-07-2020 08:45 PM')
console.log(date)
options.timeZone = 'Europe/Ulyanovsk';
options.timeZoneName = 'short';
console.log(new Intl.DateTimeFormat('en-US', options).format(date));

How to modify date format taken from Wordpress API?

By taking data from Wordpress API I'm getting date/time this way - 2019-11-29 19:00:00
How to modify it by making look like this - November 29, 2019 19:00
HTML:
<p class="date">DATE</p>
JS:
const date = postCopy.querySelector(".date");
date.textContent = post.event_date
I suggest using the toLocaleDateString() method available in vanilla JS.
Relevant doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
let initialDate = "2019-11-29 19:00:00"
let formattedDate = new Date(initialDate).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: '2-digit',
hour: "2-digit",
minute: "2-digit",
hour12: false
})
console.log(formattedDate)
If you don't like this approach, take a look at the 51 solutions proposed in this similar question: How to format a JavaScript date

How to format date into Arabic with English numerals for date and year in JavaScript?

I want the date to be formatted in the following format:
date: 2016-12-04 into الأحد، 4 ديسمبر، 2016
But I'm getting the following. The numbers are converted to Arabic numerals. I want the date and year in English numerals:
الأحد، ٤ ديسمبر، ٢٠١٦
I have used the following code to format the date to Arabic.
var date = new Date('2016-12-04');
options = {
weekday: 'long',
year: 'numeric',
month: 'short',
day: 'numeric',
};
var dateString = date.toLocaleDateString('ar-SA', options);
alert(dateString);
Found a solution Date conversion and manipulation in javascript with Arabic months
My modified code to get my desired output is as follows.
var date = new Date('2016-12-04');
var months = ["يناير", "فبراير", "مارس", "إبريل", "مايو", "يونيو",
"يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"
];
var days = ["اﻷحد", "اﻷثنين", "الثلاثاء", "اﻷربعاء", "الخميس", "الجمعة", "السبت"];
var delDateString = days[date.getDay()] + ', ' + date.getDate() + ' ' + months[date.getMonth()] + ', ' + date.getFullYear();
console.log(delDateString); // Outputs اﻷحد, 4 ديسمبر, 2016
You can use this Locales to specify numbering system.
let date = newDate.toLocaleDateString('ar-EG-u-nu-latn',{weekday: 'long', year: 'numeric', month: 'short', day: 'numeric'});
also check this MDN link to know more about it
A better (safer) way to get the Hijri (Islamic) date in English Numerals (Western-Arabic Numbers) in javascript is NOT to use a specific country locale like "ar-SA" or "ar-TN" or "ar-EG"; but use the Intl.DateTimeFormat() constructor with the following Locale options:
The numbering system (nu) set to latn (i.e. Western-Arabic Numbers), and
Calendar type (ca) set to islamic, and
The language locale to ar
The Locale options can be passed as an array for multiple options: ["ar-u-ca-islamic","ar-u-nu-latn"]
or as one string : "ar-u-ca-islamic-nu-latn"
Here is an example code that will print today's Hijri (Islamic) date with Western-Arabic Numbers (English Numerals):
I have also included a table to give the list of all Arabic "ar" locales and the default outputs to see the difference between them with regards to the name of the months and the default number system.
let options = {day: 'numeric', month: 'long',weekday:'long',year:'numeric'};
// 1st method
let locales = ["ar-u-ca-islamic","ar-u-nu-latn"];
console.log(new Intl.DateTimeFormat(locales, options).format(Date.now()));
// 2nd method
locales = "ar-u-ca-islamic-nu-latn";
console.log(new Intl.DateTimeFormat(locales, options).format(Date.now()));
To get the current hijri date in javascript, we can use Intl.DateTimeFormat
To get the arabic display :
new Intl.DateTimeFormat('ar-TN-u-ca-islamic', {day: 'numeric', month: 'long',weekday: 'long',year : 'numeric'}).format(Date.now());
the expected output :
السبت، 4 صفر 1443 هـ
https://medium.com/#Saf_Bes/get-today-hijri-date-in-javascript-90855d3cd45b
Try 'ar-MA' (for Morocco) instead of 'ar-SA'.

Categories

Resources