This question already has an answer here:
How to convert dates to UNIX timestamps in MomentJS?
(1 answer)
Closed 2 years ago.
How can I convert this date format (2020-08-18T08:00:00), to milliseconds in javascript?
I'm using momentJS, but I haven't found how to do this conversion.
Thanks!!!
You can create a new Date and use getTime(). Because of absence of timezone it's calculated on the users timezone and not UTC or serverside timezone.
Edited: Because different browser (e.g. Safari and Firefox) produce different results Why does Date.parse give incorrect results? I changed my code so is the date now generated by a secure method by programatical and not automatic parsing of the datestring.
In the old version I had: let date = new Date(dateStr); which works on the most browser but not on all as RobG mentioned.
let dateStr = '2020-08-18T08:00:00';
let parts = dateStr.split('T');
let datParts = parts[0].split('-');
let timeParts = parts[1].split(':');
let date = new Date(datParts[0], datParts[1]-1, datParts[2], timeParts[0], timeParts[1], timeParts[2]);
let ms = date.getTime()
console.log(ms);
You can pass that entire string to Date.parse() to get the milliseconds.
A caveat though: As others have pointed out, your date lacks a timezone so you'll be limited to the timezone in which the script is run.
const millis = Date.parse('2020-08-18T08:00:00');
console.log(millis);
console.log(new Date(millis));
Related
This question already has answers here:
How to ISO 8601 format a Date with Timezone Offset in JavaScript?
(21 answers)
Javascript date format like ISO but local
(12 answers)
Closed last year.
Hi i have a date that arrive with this format 2020-05-25T20:11:38Z, and i need to convert to 2020-05-25T21:11:38+01:00.
In my project is not installed moment.js is a big project, and the masters don't use it.
is there some where to make this change?
I have the timeZone for every zone.
I know that there is options like this getTimezoneOffset();
And i did find in stackoverflow, but i didn't find any response in javascript to change zulu to utc with offset.
Thanks for your indications
The format "2020-05-25T20:11:38Z" is a common standard ISO 8601 format, it is also produced by the default Date.prototype.toString method, however it's only with a UTC (+0) offset.
The above ISO 8601 format is reliably parsed by reasonably current built–in parsers (some very old implementations won't parse it correctly), so to get a Date object:
let date = new Date('2020-05-25T20:11:38Z');
Formatting it for a fixed +1 offset can done by adjusting the Date for the offset then formatting it as required by leveraging the default toISOString method, e.g.
// Initial timestamp
let s = '2020-05-25T20:11:38Z'
// Convert s to a Date
let d = new Date(s);
// Show that it's the same date
console.log(`Initial value: ${s}\n` +
`Parsed value : ${d.toISOString()}`);
// Create a new date with 1 hour added as 3,600,000 milliseconds
let e = new Date(d.getTime() + 3.6e6);
// Format and manually modify the offset part
let timestamp = e.toISOString().replace('Z','+01:00');
console.log(`Adjusted timestamp: ${timestamp}`);
// Parse back to date
console.log(`Parsed to a Date : ${new Date(timestamp).toISOString()}`);
The resulting timestamp can be parsed back to a Date that represents the same instant in time as the original string (last line).
Note that the adjusted Date is only created for the sake of formatting the timestamp, it shouldn't be used for anything else.
If, on the other hand, you want a general function to format dates as ISO 8601 with the local offset, there is likely an answer at Javascript date format like ISO but local that suits. If so, then this is a duplicate, e.g. this answer or this one.
Also, there are a number of libraries that will allow specifying the formatting and timezone as separate parameters, so consider using one if you're going to do a lot of date formatting or manipulation.
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 1 year ago.
I have a date and time in ISO
"time": "2021-10-28T17:30:00.000Z"
Below is what I am doing right now to extract the date and time:
var dateExtract = time.substring(0, 10);
var timeExtract = time.match(/\d\d:\d\d/);
But it is giving me the exact date and time written in ISO.
What I want is to extract the date and time in local date and time. I don't know how to do this.
Use the Date instance.
let obj = {"time": "2021-10-28T17:30:00.000Z"}
const dateTime = new Date(obj.time);
const date = dateTime.toLocaleDateString().replace(/\//g, '-');
// '28-10-2021'
const time = dateTime.toLocaleTimeString()
// '18:30:00' since I am in (+1)
Also find a pool of answers in this similar Question
Just create a date object and use toLocaleString or toLocaleDateString or
toLocaleTimeString
const date = new Date("2021-10-28T17:30:00.000Z")
console.log(date.toLocaleString())
console.log(date.toLocaleDateString().replaceAll("/","-"))
console.log(date.toLocaleTimeString())
You are getting dates in a wrong method.
when you are reading the date it should be converted to your locale, so that you will get exact date from UTC date
You can use JS Date() function or moment library
let d = new Date("2021-10-28T17:30:00.000Z")
d.toDateString()
d.toLocaleDateString()
check Date functions to get date, month, year, time , seconds or timestamp
refer How to format a JavaScript date
https://www.w3schools.com/js/js_dates.asp
https://www.w3schools.com/js/js_date_formats.asp
Or you can use the external moment library
https://momentjs.com/
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
I'm trying to convert data using JS ES6 Intl.DateTimeFormat("pt-BR"), but everything i get is the previous day. Code i'm using:
var a = new Intl.DateTimeFormat("en-US");
var b = new Intl.DateTimeFormat("pt-BR");
console.log(a.format(new Date("2015-01-02"))); // "1/1/2015"
console.log(b.format(new Date("2015-01-02"))); // "01/01/2015"
Thank you in advance.
It is discouraged to rely on Date parsing a string. According to mdn:
Parsing of date strings with the Date constructor (and Date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies.
The format you use (yyyy-mm-dd) is interpreted as a UTC date (at midnight), so it does not correspond with your local date.
So better break down the string yourself into numerical arguments, and pass those to the Date constructor:
var a = new Intl.DateTimeFormat("en-US");
var b = new Intl.DateTimeFormat("pt-BR");
let date = new Date(..."2015-01-02".match(/\d+/g).map((d, i) => d-i%2));
console.log(a.format(date)); // "1/1/2015"
console.log(b.format(date)); // "01/01/2015"
The problem is related to timezone. The output is in your timezone, at 00:00 of the day 2nd of January UTC is 1st January 21:00 at your timezone, considering that your timezone is, for example, America/Sao_Paulo.
see: doc from mozilla
timeZone
The time zone to use. The only value implementations must recognize is "UTC"; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as "Asia/Shanghai", "Asia/Kolkata", "America/New_York".
This question already has answers here:
Convert a Unix timestamp to time in JavaScript
(34 answers)
Closed 5 years ago.
Pretty straightforward issue, but I haven't found any information on this after looking around a bunch.
Essentially, I want to convert a series of UTC dates (e.g. "1505952000") into regular date strings (e.g., "9/21"), to use today as an example.
For some reason, however, .toDateString() is erroring out as "not a function" when I try to run it. How do I make this simple conversion work?
Here's my code, and I've console-logged day.dt to ensure that it's a valid UTC date when it runs:
let dt = day.dt.toDateString();
UTC var stored in seconds from Jan. 1, 1970.
So to convert it back to the local date time, use this snippet:
var d = new Date(0);
d.setUTCSeconds(1505952000);
console.log(d);
OR
var d = new Date(1505952000 * 1000); // Because this constructor takes miliseconds.
console.log(d);
This question already has answers here:
How do I get a UTC Timestamp in JavaScript?
(16 answers)
Closed 10 years ago.
How can I get the current UTC timestamp in JavaScript? I want to do this so I can send timestamps from the client-side that are independent of their timezone.
new Date().getTime();
For more information, see #James McMahon's answer.
As wizzard pointed out, the correct method is,
new Date().getTime();
or under Javascript 1.5, just
Date.now();
From the documentation,
The value returned by the getTime method is the number of milliseconds
since 1 January 1970 00:00:00 UTC.
If you wanted to make a time stamp without milliseconds you can use,
Math.floor(Date.now() / 1000);
I wanted to make this an answer so the correct method is more visible.
You can compare ExpExc's and Narendra Yadala's results to the method above at http://jsfiddle.net/JamesFM/bxEJd/, and verify with http://www.unixtimestamp.com/ or by running date +%s on a Unix terminal.
You can use Date.UTC method to get the time stamp at the UTC timezone.
Usage:
var now = new Date;
var utc_timestamp = Date.UTC(now.getUTCFullYear(),now.getUTCMonth(), now.getUTCDate() ,
now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
Live demo here http://jsfiddle.net/naryad/uU7FH/1/
"... that are independent of their timezone"
var timezone = d.getTimezoneOffset() // difference in minutes from GMT