How should I convert a date format of YYYY-MM-DD into a human readable format %e %B %Y in JS by taking into an account a different language from system's locale?
In PHP it would be like
<?php echo trim(strftime('%e %B %Y', strtotime('2019-07-31'))); ?>
// Renders: 31 July 2019
I want to have the same, but with a corresponding language locale, for example "French format" so it will become : 31 Juillet 2019
==== UPDATED ====
As mention by #Baljinder Singh, solution below from the link, works perfectly
console.log(
new Date('2019-07-31').toLocaleDateString('fr-FR', {
year: 'numeric',
month: 'long',
day: 'numeric'
})
)
If it's browser-specific then you can make it dynamic with window.navigator.language.
const date = new Date('2019-07-31').toLocaleDateString(window.navigator.language, {
year: 'numeric',
month: 'long',
day: 'numeric',
});
console.log(date);
Notice: Working fine in chrome and firefox.
Try
let d = new Date('2019-08-20');
let s = d.toLocaleDateString(navigator.languages,{day:"numeric", month:"long", year: "numeric"});
console.log(s);
Related
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.
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));
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
I am trying to format date in 'MM/dd/yyyy' (short date format) using toLocaleString function of javascript Date. But it is not giving expected result when I change my timezone. Bellow is snippet of my code
var d1 = new Date(1954, 0, 1); // Fri Jan 01 1954 00:00:00 GMT-0900 (AKST)
var options = {
year: 'numeric',
month: '2-digit',
day: '2-digit'
};
var shortDate = d1.toLocaleString('en-US', options);
console.log(shortDate);
Above code prints 12/31/1953 instead of expected result which is 01/01/1954.
Observations/Steps:
Change timezone of local machine to Whitehorse - Canada(Pacific DayLight Time).
Run above code snippet to replicate result.
It only gets reproduced for year value less than 1968 (works fine for years greater than 1968)
For reference, uploaded recording for it (http://recordit.co/cdWMgWFLKJ)
local date time function is a conversion from UTC to locale date time. You need to change UTC time first.
so use this.
var d1 = new Date(Date.UTC(1954, 0, 1)); // Fri Jan 01 1954 00:00:00 GMT-0900 (AKST)
var options = {
year: 'numeric',
month: '2-digit',
day: '2-digit'
};
var shortDate = d1.toLocaleString('en-US', options);
console.log(shortDate);
The string that is returned from (new Date()).toString() looks something like this:
"Tue Nov 22 2016 14:14:51 GMT-0800 (Pacific Standard Time)"
Is there a built-in method/constructor that we can use that will not abbreviate the day-of-week and/or month? In other words, does JS support this:
"Tuesday November 22 2016 14:14:51 GMT-0800 (Pacific Standard Time)"
The reason for my question is because I'm looking for a lazy/hacky way that we might be able to get the Weekday and Month names in the language of the client.
If you don't need to support old browsers (older than IE 11), you can use toLocalDateString().
Example:
new Date().toLocaleDateString('en-US', {
weekday: 'long',
month: 'long',
day: 'numeric',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short'
})
But moment.js is way more comfortable.
See MDN Date.prototype.toLocaleDateString() for more information.
As Josa's answer implies, it is possible to get the full names for the weekday and month (for most modern browsers).
I used the .toLocaleDateString() to extract the full names of the weekday and month in the language of the client successfully using Chrome and IE11 (it does NOT work in Safari 9).
Extending the idea of getting the full names from the browser, I was curious if we could, then, get the name of the weekday and the name of the month in the language that matches the client's locale. The following experiment shows that that it is possible (although, not reliable).
For Experiment/Fun:
The following function will return an object that includes the name of the Weekday and Month for a particular date in the language of a particular locale-code.
Fiddle
function getWeekdayAndMonthNamesByLocaleCode(localeCode, date) {
var Names = {
Weekday: "",
Month: ""
};
if (!(date instanceof Date && !isNaN(date.valueOf()))) {
date = new Date();
}
if (localeCode == null || localeCode.length < 2) {
localeCode = navigator.language;
}
Names.Month = date.toLocaleDateString(localeCode, {
month: 'long',
});
Names.Weekday = date.toLocaleDateString(localeCode, {
weekday: 'long'
});
return Names;
}
I haven't tested the function for browser compatibility and I certainly wouldn't rely on it to work for all languages, but I thought it was interesting enough to post here for others to experiment with.