I have a date and need to convert it into this format
02/27/2020 3:00PM (MST)
What is the fastest way to do that in javscript like a one liner?
I tried
var options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute:'numeric', timeZoneName: 'short' };
this.date = new Date().toLocaleDateString("en-US", options);
This also does not work
new Date().toLocaleDateString(Intl.DateTimeFormat().resolvedOptions().timeZone, options);
as I am getting asia/caluctta invalid language tag
While this works for UnitedStates this does not work for users in russia, india, europe, china.
It will show the date as
02/28/2020 +500 GMT
I need it to show as
02/28/2020 (IST) for India
or
02/28/2020 (JST) for Japan Standard time
I can recommend you to try Moment.js. It's a javascript library made especially for easier manipulation with time. Just download the .js and add it to your index.html before your script.
Related
I'm trying to convert the string 2022-02-01T13:36:57+00:00 to a Date object javascript that returns me Tue Feb 01 2022 13:36:57 without considering the timezone.
But everytime that I try to convert the date it returns:
Tue Feb 01 2022 10:36:57 GMT-0300 (Brasilia Standard Time)
I already tried with moment:
let now = moment("2022-02-01T13:36:57+00:00").toDate();
with Date:
let now = new Date("2022-02-01T13:36:57+00:00");
with UTC too: new Date(Date.UTC(2022, 02, 01, 10, 36, 57))
But all of them returns me the local date (Brasilia Standard Time)
So, the question is:
How can I convert this string 2022-02-01T13:36:57+00:00 to a Date object that keeps the same day, hour, etc ?
The timestamp "2022-02-01T13:36:57+00:00" represents a unique moment in time. If parsed to a Date object, it will create a Date instance with a time value of 1643722617000, which is the offset in milliseconds from the ECMAScript epoch of 1 Jan 1970.
The time value produced from the timestamp is unaffected by local settings as:
It conforms to one of the formats supported by ECMA-262 and therefore parsing is specified by the standard
Contains a fixed offset
The default toString method produces a timestamp for the equivalent date and time in the timezone of the host system, typically called the local date and time. It will produce a different date and time for each host with a different offset, but they will all represent exactly the same moment in time.
E.g.
let timestamp = '2022-02-01T13:36:57+00:00';
let date = new Date(timestamp);
['UTC','America/Sao_Paulo','Asia/Kolkata'].forEach(
loc => console.log(`${date.toLocaleString('default',{timeZone:loc})} - ${loc}`)
)
If you want the timestamp to be parsed as local (and that should only be done if you know what you are doing and have a very good reason to do so) then remove the offset and parse the remainder:
let timestamp = '2022-02-01T13:36:57+00:00';
let date = new Date(timestamp.substring(0,19));
console.log(date.toString());
Note that the resulting Date represents a different moment in time for each host with a different offset and each such date instance will have a different time value.
You can instantiate your own Intl.DateTimeFormat formatter, or call Date.prototype.toLocaleString().
const
dateString = '2022-02-01T13:36:57+00:00',
date = new Date(dateString),
dateFormatter = new Intl.DateTimeFormat('en-US', {
timeZone: 'UTC',
weekday: 'short',
year: 'numeric',
month: 'short',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'long',
hour12: false
});
console.log(`Local date : ${date}`);
console.log(` UTC date : ${dateFormatter.format(date).replace(/,/g, '')}`);
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 2 years ago.
I have a date: yyyy-mm-dd that I am formatting using the International DateTimeFormat like this:
const formatter = new Intl.DateTimeFormat("en-US", { month: '2-digit', day: '2-digit', year: 'numeric', timeZone:'America/Denver'});
// GiVES SAME RESULTS AS ABOVE
//const formatter = new Intl.DateTimeFormat("en-US", { month: '2-digit', day: '2-digit', year: 'numeric'});
//const formatter = new Intl.DateTimeFormat("default" , { month: '2-digit', day: '2-digit', year: 'numeric'});
let date = "2020-03-19"
return formatter.format(Date.parse(date));
//returns 03/18/2020 which is one day behind
I've tried this with and without the timeZone attribute. How can I fix this?
The ECMAScript Date Time String Format defines formats for both date-time forms as well as date-only forms. These are used by the Date.parse function and the Date constructor when a string is passed. Behavior for those functions is defined in the docs for the Date.parse function, which contain the following statement:
... When the UTC offset representation is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
Thus, when you call Date.parse('2020-03-19') the defined behavior is to treat that as UTC, not as local time. (This deviates from ISO 8601.)
To change this behavior, append a time string or a time+offset string.
For example, if you want to parse the time in the local computer's time zone:
Date.parse('2020-03-19T00:00:00.000')
Or, if you want to parse in a particular time zone and know the correct offset for the given timestamp in that time zone:
Date.parse('2020-03-19T00:00:00.000-05:00')
Often one doesn't know the offset, but does know the IANA time zone identifiers (such as 'America/Chicago'). Unfortunately, ECMAScript doesn't currently have the capability to parse in a named time zone yet. That capability will be possible if/when the TC39 Temporal proposal is adopted. Until then, you could use a library such as Luxon to perform such an action. For example:
luxon.DateTime.fromISO('2020-03-19', { zone: 'America/Chicago' }).toString()
//=> "2020-03-19T00:00:00.000-05:00"
Date.parse("2020-03-19") indicates 2020-03-19 00:00:00 GMT, so it will be 2020-03-18 for America/Denver, which will be 2020-03-18 17:00:00 America/Denver
const formatter1 = new Intl.DateTimeFormat("en-US", { month: '2-digit', day: '2-digit', year: 'numeric', timeZone:'America/Denver'});
const formatter2 = new Intl.DateTimeFormat("en-US", { month: '2-digit', day: '2-digit', year: 'numeric'});
let date = "2020-03-19"
console.log(formatter1.format(Date.parse(date)));
console.log(formatter2.format(Date.parse(date)));
You have added time zone, because of that it convert date into that time zone and because of the zone it can be 1 day behind or next day.
Is there any javascript library which can parse string created by Intl.DateTimeFormat and give a Date?
For example:
options = {
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
weekday: "short",
}
var test_date = new Date();
console.log(new Intl.DateTimeFormat('hr', options).format(test_date));
// note that test_date is just an example.
// We need to parse text created Intl.DateTimeFormat and give a Date.
will return:
sub, 21. ožu 2020. 12:41
That is great - exactly how it should be written.
But how to parse it back to be a Date?
Something like:
Date.parse('sub, 21. ožu 2020. 12:41', options, 'hr')
// hr is locale
// options are same a options given to Intl.DateTimeFormat
We tried momentjs and format 'llll', but sadly momentjs locale are different that Intl.DateTimeFormat implementation on Google Chrome (i.e., dots are added in wrong places, abbreviations for dates are incorrect, etc.). We tested with 'hr', 'sk', and few others and no luck :(
So is there any library which any javascript library which can parse string created by Intl.DateTimeFormat?
I'm developing a API Proxy in Apigee API Platform. I'm using a Javascript script to convert a Date to a User-Friendly representation.
So I have this code:
var endDate = new Date(2014, 01, 01, 00, 00, 00);
var options = {
localeMatcher: 'best fit',
weekDay: 'short',
year: 'numeric',
month: 'short',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timezone: 'America/El_Salvador',
timeZoneName: 'short'
};
var friendly_endDate = endDate.toLocaleDateString('es-SV', options);
And I always end up with a en-US formatted date like the following:
February 1, 2014 12:00:00 UTC
Timezone, options and locale is ignored. is this normal? Am I missing something?
The latest version of Rhino (1.7R4) was released on 6/18/2012. According to the Mozilla docs on Date.toLocaleDateString, the locales and options arguments were added with the ECMAScript Internalization API, which looks like it came out in December 2012.
I think your best bet is to find a JavaScript library that can be included for your policy, and use that. See the Apigee JavaScript policy documentation for instructions on including JavaScript libraries.
I use moment JS libray. Very nicely design simple library for JS base Date manipulations. Give it a try.
We also have a working sample that shows you how to work with JavaScript libraries as includes in an API proxy:
https://github.com/apigee/api-platform-samples/tree/master/sample-proxies/base64encoder
I need to get the date in a specific locale using JavaScript - not necessarily the user's locale. How can I do this?
I did some research and found date.getUTCMonth() and date.getUTCDate(). How can I use this or something else to get the date in a certain locale?
You can use toLocaleDateString:
From the MDN documentation:
The new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function.
const event = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(event.toLocaleDateString('de-DE', options));