This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
Let's say that I receiving a date from api in format: 20191116T202021.000Z
But unfortunately I'am not able to parse this data in javascript:
var dateToParse = "20191116T202021.000Z"
var dateFormat = "YYYYMMDD'T'HHmmss.sss'Z'"
var test = Date.parse(dateToParse, dateFormat)
console.log(test)
What I want to achieve is to subtract current date with this dateToParse date and see difference in seconds, minutes and days.
There is no second argument support for Date.parse. Instead convert your input string to the ISO format by inserting the missing delimiters:
var dateToParse = "20191116T202021.000Z";
var test = Date.parse(dateToParse.replace(/(....)(..)(..T..)(..)/, "$1-$2-$3:$4:"));
console.log(test); // output as milliseconds
console.log(new Date(test).toJSON()); // output also in JSON format
As noted below, the above regular expression already does the work of parsing the string into its date parts, so you might as well pass those parts to Date.UTC without building another string that needs parsing again. It just needs a little adjustment for the month number:
var dateToParse = "20191116T202021.000Z";
var parts = dateToParse.match(/(....)(..)(..)T(..)(..)(..)\.(...)Z/);
var test = Date.UTC(parts[1], parts[2]-1, parts[3], parts[4], parts[5], parts[6], parts[7]);
console.log(test); // output as milliseconds
console.log(new Date(test).toJSON()); // output also in JSON format
For more efficiency you would just slice the string into its fixed size pieces without the fancy regular expression:
var dateToParse = "20191116T202021.000Z";
var test = Date.UTC(dateToParse.slice(0,4),
dateToParse.slice(4,6)-1,
dateToParse.slice(6,8),
dateToParse.slice(9,11),
dateToParse.slice(11,13),
dateToParse.slice(13,15),
dateToParse.slice(16,19));
console.log(test); // output as milliseconds
console.log(new Date(test).toJSON()); // output also in JSON format
Related
This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 5 months ago.
When working with the task, it became necessary to get dates from html, and to find out the time difference between them:
var now_time_div = document.getElementById("time_now_of");
var start_time_div = document.getElementById("time_when_start_of");
var time_now = now_time_div.textContent || now_time_div.innerHTML;
var time_start = start_time_div.textContent || start_time_div.innerHTML;
After that, without thinking about the format of the data, I wanted to find the time difference in ms:
var worked_time = time_now - time_start
That didn't work, because we are working with a string.
After entering the directory, I found the Date.parse() function, which returns the amount of time that has passed since the given date:
var worked_time = Date.parse(time_start);
but it turned out that it works only with a correctly submitted strig, for example
We need to have:
Date.parse('01 Jan 1970 00:00:00 GMT');
We have:
Date.parse('21.09.2022, 15:34:21')
Maybe someone knows an easy way to implement this without rebuilding the string?
If you don't want to bring in a library like moment.js, you can just massage the date string a bit so it can be parsed correctly
const dateString = '21.09.2022, 15:34:21';
const curDate = dateString.split(',')[0].substring(0, 10).split('.');
const curTime = dateString.split(',')[1];
const parsed = `${curDate[1]}'/'${curDate[0]}'/'${curDate[2]} ${curTime}`;
console.log(new Date(parsed).toString()); // Properly formatted date
You can used this parsed variable to compare to other properly formatted dates
You can use moment.js to parse custom date formats just as in for example Java:
https://momentjs.com/docs/#/parsing/string-format/
After that you can simply convert it to a js date using the toDate function: https://momentjs.com/docs/#/displaying/as-javascript-date/
Edit Example:
var mDate = moment('2022-09-21 10:15:00', 'YYYY-MM-DD HH:mm:ss');
var jsDate = mDate.toDate();
This question already has answers here:
Converting milliseconds to a date (jQuery/JavaScript)
(12 answers)
Closed 1 year ago.
I have seen a variety of threads that are adjacent to this topic. However, my google fu has failed me so far.
I have a value on my server that is a date represented as a string. I am certain it is the milliseconds since the UTC epoch.
I will write it like this for stackOverflow:
const k = '1638400203941'
Date.parse(k); // NaN
const a = parseInt(k, 10);
Date.parse(a); // NaN
// ah ha! but what about...
Date.parse(Date.now() - a); // nope, NaN
I am sure this has been done a thousand times before but how do I do this?
To clarify, the goal is to parse my server's output, k = 1638400203941 into a date. YYYY-MM-DD or MM-DD-YYYY is ok.
edit: Somehow I didn't think to try the given solution. It was giving me Invalid date for some reason, guessing that I was passing in the string version instead of int. My mistake guys.
Just use new Date with you time in numerical format. I used + to convert the string to number.
const k = '1638400203941'
console.log(new Date(+k));
This question already has answers here:
Format JavaScript date as yyyy-mm-dd
(50 answers)
Closed 2 years ago.
I have date string in the format '2020/02/25 23:58:08' . I want to parse it to '2020-02-25".
Note : Initially date is in string format, after conversion whether it is in date or string format it doesn't matter.
file.js
function test (filepath) {
let date = "2020/02/25 23:58:08";
date = date.replace("//"/gi,"-");
// I am not familiar with regular expressions, I want to omit the data related to hours, seconds extra
}
When I ran the program, I gotUncaught ReferenceError: gi is not defined, gi is to globally replace
Try this
let date = "2020/02/25 23:58:08";
var date2 = new Date(date)
console.log(date2.toISOString().slice(0,10))
let date = `2020/02/25 23:58:08`;
let parsedDate = date.split(" ")[0].replace(/\//gi,'-');
console.log(parsedDate);
There is an error in the line using regex, should be:
let date = "2020/02/25 23:58:08";
date = date.replace(/\//gi,"-");
Then to get only the date, you can get the first 10 characters:
date.slice(0,10)
Final code:
let date = "2020/02/25 23:58:08";
date = date.replace(/\//gi,"-");
date.slice(0,10)
Although there are other ways to do it, you can use a library like momentJs which includes methods for this, like moment.format, it gives so many possibilities. But if you have a small case this is fine.
This question already has answers here:
javascript: how to parse a date string
(4 answers)
Closed 5 years ago.
In javascript, while using exif-js to extract metadata of an image file, I am getting date time format as 2017:03:09 14:49:21.
The value in the DateTimeOriginal property is formatted as YYYY:MMY:DD HH:MM:SS. When I use var d = new Date(2017:03:09 14:49:21), it returns NaN. It's the colons in between the YYYY, MM, and DD which causes problem.
How to solve this problem?
Thanks in advance.
Don't use the built-in parser (i.e. Date constructor or Date.parse) for parsing strings as it's largely implementation dependent and unreliable. If you can trust the date to be valid, then the following will do:
/* Parse date string in YYYY-MM-DD hh:mm:ss format
** separator can be any non-digit character
** e.g. 2017:03:09 14:49:21
*/
function parseDate(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
}
console.log(parseDate('2017:03:09 14:49:21').toString());
It's fairly easy to add validation to the values. Otherwise, use a library and make sure you specify the format to parse.
My recommendation would be to use Moment (http://momentjs.com/docs/), as it provides clean parsing of dates. With Moment, what you want is this:
var tstamp = moment("2017:03:09 14:49:21", "YYYY:MM:DD HH:mm:ss");
var date = tstamp.toDate();
You can do simple string manipulation and create date if the format is always the same, as:
var str = "2017:03:09 14:49:21".split(" ");
//get date part and replace ':' with '-'
var dateStr = str[0].replace(/:/g, "-");
//concat the strings (date and time part)
var properDateStr = dateStr + " " + str[1];
//pass to Date
var date = new Date(properDateStr);
console.log(date);
This question already has answers here:
Converting 24 hour time to 12 hour time w/ AM & PM using Javascript
(24 answers)
Closed 5 years ago.
I have this time in a variable called lastdate in javascript.
07:31:00
How can I show AM or PM using format specifier in Javascript..Like I use in php "%p" .
Is there any method to use in javascript. Any help is much appreciated.
Assuming that your time string will be in 24H format:
1.) Split time string into array.
2.) Create new Date object.
3.) Map the array to create integers. (this can also be done on each variable in the below method)
4.) Set the hours, minutes, and seconds to values of the generated array.
5.) Convert Date object to the local time string and use a Regex to create your new time string. (NOTE: toLocaleTimeString() may behave differently based on location)
/* Variable Defaults */
var timeString = '07:31:00';
var parts = timeString.match(/(\d{2}):(\d{2}):(\d{2})/);
var dateObject = new Date();
/* Cast `parts` as Integer */
Object.keys(parts).map(function(key, index) {
parts[key] = parseInt(parts[key]);
});
/* Set Hours/Minutes/Seconds */
dateObject.setHours(parts[1]);
dateObject.setMinutes(parts[2]);
dateObject.setSeconds(parts[3]);
/* Output New String */
var newTimeString = dateObject.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, '$1$3')
/* Console Result */
console.log(newTimeString);
If you can bring in an external library, I'd recommend moment.js.
https://momentjs.com/
Then you can specify what you want with:
var lastdate = "07:31:00"
moment(lastdate, 'HH:mm:ss').format('LTS'); // 07:31:00 AM
Or if you want to be more explicit:
var lastdate = "07:31:00"
moment(lastdate, 'HH:mm:ss').format('HH:mm:ss A'); // 07:31:00 AM
Where the A means AM/PM. See https://momentjs.com/docs/#/displaying/format/.