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);
Related
This question already has answers here:
Use JavaScript to convert a date string with timezone to a date object in local time
(3 answers)
Closed 5 months ago.
My app gets an array of events from an external source. Each event has a start date like 20220925000000 +0000. The format is YYYYMMDDHHMMSS and the last part is timezone which is not always +0000.
I need to store the events and show the right start date and time to each user (Around the globe) based on their timezone. I've searched and read some SO questions but it is still confusing to me. What is the correct approach?
// first parse the date using a regex:
const [m, year, month, day, hours, minutes, seconds, timezone] = '20220925000000 +0000'.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2}) (\+\d{4})/);
// Then log it with proper input format for date object:
const str = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}${timezone}`;
// pass it to Date constructor and call `toLocaleString()` to get user's local format.
console.log(new Date(str).toLocaleString());
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));
This question already has answers here:
Convert a Unix timestamp to time in JavaScript
(34 answers)
Closed 2 years ago.
I'm looking for something to convert exact time
var arr = [1585287883,1585287876,1585287736,1585287730,1585287725,1585287720];
arr.forEach(val=>{
console.log(Date(val).toString())
})
There are 2 issues with what you posted:
Date -> new Date
The timestamps in javascript should represent milliseconds, currently they represent seconds. You can multiply the timestamps by 1000 when building the date object, to convert seconds to milliseconds.
var arr = [1585287883,1585287876,1585287736,1585287730,1585287725,1585287720];
arr.forEach(val=>{
console.log(new Date(val*1000).toString())
})
The fact is that you're using the wrong input format. Instead of seconds since 1970-01-01, you should use milliseconds.
A JavaScript date is fundamentally specified as the number of
milliseconds that have elapsed since midnight on January 1, 1970, UTC.
This date and time is the same as the UNIX epoch, which is the
predominant base value for computer-recorded date and time values.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Simply, multiply you're input by 1000 (and use the keyword new ;) )
var arr = [1585287883,1585287876,1585287736,1585287730,1585287725,1585287720];
arr.forEach(val=>{
console.log(new Date(val * 1000).toString());
})
This question already has answers here:
Parse date without timezone javascript
(16 answers)
Closed 4 years ago.
Input: I have a date string: "2018-11-30T01:00:00+11:00"
Usecase: I need to convert it into Date object using plain js or with any library.
Result: I should receive a date object with date part as "2018-11-30" and time part as "1:00".
Please help. I've tried every solution but the time always changes to match my machine's timezone. I don't want that behavior neither do I want to do complicated time conversions on my backend.
This is the solution that I came up with for this problem which actually works.
library used: momentjs with plain javascript Date class.
Step 1.
Convert String date to moment object (PS: moment retains the original date and time as long as toDate() method is not called):
const dateMoment = getMomentFromIsoString(date);
Step 2.
Extract hours and minutes values from the previously created moment object:
const hours = dateMoment.hours();
const mins = dateMoment.minutes();
Step 3.
Convert moment to Date(PS: this will change the original date based on the timezone of your browser/machine, but don't worry and read step 4.):
const dateObj = dateMoment.toDate();
Step 4.
Manually set the hours and minutes extracted in Step 2.
dateObj.setHours(hours);
dateObj.setMinutes(mins);
Step 5.
dateObj will now have show the original Date without any timezone difference. Even the Daylight time changes won't have any effect on the date object as we are manually setting the original hours and minutes.
Hope this helps.
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