I have a requirement to send the current system date to microservices on search. The time should include milliseconds information as well. For now I was sending new Date() for the same and it looked like:
Thu Aug 31 2017 15:06:37 GMT+0530 (India Standard Time)
However I need the milliseconds information as well so the time should look like:
Thu Aug 31 2017 15:06:37.228 GMT+0530 (India Standard Time)
Here 228 is the millisecond at that moment that I can extract using getMilliseconds() method of date. The question is how can I add this in the date so that it works for all locations wherever the application is accessed?
If you don't mind having the result as a string, this will show the output you are looking for:
// ES5
var fmtDateMsES5 = function(date) {
var splitDate = date.toString().split(' ');
splitDate[4] = splitDate[4] + '.' + date.getMilliseconds();
return splitDate.join(' ');
}
// log output (ES5)
console.log('ES5 output\n', fmtDateMsES5(new Date()));
// ES6
const fmtDateMsES6 = date => {
const splitDate = date.toString().split(' ');
splitDate[4] = `${splitDate[4]}.${date.getMilliseconds()}`;
return splitDate.join(' ');
};
// log output (ES6)
console.log('ES6 output\n', fmtDateMsES6(new Date()));
// ES5 and ES6 functions logged simultaneously
console.log(
`\nES5 and ES6 functions logged simultaneously`,
`\n${'-'.repeat(55)}`,
`\nES5 output ${fmtDateMsES5(new Date())}`,
`\nES6 output ${fmtDateMsES6(new Date())}`
);
Initially I saw the format method on the Date object but this is not built-in and requires a library.
If you must use a time library I would recommend the excellent moment.js and use the "SSS" syntax to get the milliseconds, for example:
var now = moment().format('MMM DD h:mm.SSS A');
//Sep 12 8:21.167 AM
http://jsfiddle.net/kLL2eobh/
Related
I would like to know how can I convert with a library or pure JS a date like this
Fri Mar 05 2021 13:51:35 GMT+0000 (Coordinated Universal Time)
to this format
2021-03-05 13:51:35.829058+00
As asked in comments what I was trying to achieve is to convert the shared date to specific format I tried the following stuff
1) const t = createdAt
.toISOString()
.replace('T', ' ')
.replace('Z', '');
2) Using date-fns
format(addMinutes(date, date.getTimezoneOffset()), 'yyyy-MM-dd HH:mm:ss');
The result of those tries is like
2021-03-05 14:44:11
But is not correct as I need after 11 more numbers and +00.
When you use UTCDate(), you need have a full date to get all items:
function pad(e){ return (e.toString().length<2?'0'+e:e); }
function ShowData(data){ var d = new Date(data); return d.getFullYear()+'-'+pad(d.getMonth()+1) +'-'+ pad(d.getDate())+' '+pad(d.getHours())+':'+pad(d.getMinutes())+':'+pad(d.getSeconds())+'.'+pad(d.getMilliseconds())+pad(d.getUTCDate())+"+00"; }
When you use your example:
ShowData('Fri Mar 05 2021 13:51:35 GMT+0000');
Then you got
2021-03-05 10:51:35.0005+00
When we use a full date form:
ShowData(new Date());
Then you got
2021-03-05 13:05:36.51605+00
I hope could help.
I have a really simple piece of code for moment.js (see below), it should resolve to true but instead resolves to false.
I get the same unexpected behaviour with isBefore() or isAfter(), which leads me to believe there is something wrong with how I'm defining the dates.
var format = 'YYYY-MM-DDTHH:mm:ss.SSSSZ';
var testTime = moment('Thu Jun 27 2019 05:33:19 GMT+0000', format);
var startPeriod = moment('Thu Jun 27 2019 04:00:19 GMT+0000', format);
var endPeriod = moment('Thu Jun 27 2019 10:00:19 GMT+0000', format);
console.log(
testTime.isBetween(startPeriod, endPeriod)
);
What am I missing here?
The second parameter to moment() takes in the format that the first parameter is currently in. This looks incorrect. You can verify this by logging the times individually and seeing that they're incorrect (probably 1970)
See https://momentjs.com/docs/#/parsing/creation-data/
Infact, you should be able to drop this second parameter completely as the input date is in a standard format already (an ISO string).
var testTime = moment('Thu Jun 27 2019 05:33:19 GMT+0000');
var startPeriod = moment('Thu Jun 27 2019 04:00:19 GMT+0000');
var endPeriod = moment('Thu Jun 27 2019 10:00:19 GMT+0000');
console.log(
testTime.isBetween(startPeriod, endPeriod)
);
When converting a UTC date format to timestamp this condition will always fail
const start_time = "2017-03-02T15:57:00Z";
const stop_time = "2017-03-02T17:51:00Z";
const local_timestamp = 1488498242256; // Thu Mar 02 2017 16:44:02 GMT-0700 (MST)
const start = moment(start_time).valueOf(); // 1488470220000
const stop = moment(stop_time).valueOf(); // 1488477060000
const is_between = local_timestamp >= start && local_timestamp <= stop; // false
So I tried this and still failed
const start = moment(start_time).utc().valueOf(); // 1488470220000
const stop = moment(stop_time).utc().valueOf(); // 1488477060000
const is_between = local_timestamp >= start && local_timestamp <= stop; // false
Same thing here
const now = moment(local_timestamp);
const isBetween = now.isBetween(start, stop); // false
Please help me understand this.
When converting a UTC date format to timestamp this condition will always fail
A timestamp is anything that represents a date or time, so "2017-03-02T15:57:00Z", "Thu Mar 02 2017 16:44:02 GMT-0700 (MST)" and 1488498242256 are all timestamps.
1488498242256 represents "2017-03-02T23:44:02.256Z" which is not between "2017-03-02T15:57:00Z" and "2017-03-02T17:51:00Z", so the expected result of your tests is false.
So I tried this and still failed
It's not failing, it's returning the expected result.
When you do, say:
new Date(1488498242256)
then a Date instance is created with a time value of 1488498242256, which represents "2017-03-02T23:44:02.256Z". When you write this to output that generates a string, usually Date.prototype.toString is called and a string is generated in what the browser developers have determined is a human friendly format.
Typically this means that the host system timezone offset is used to generate the string and you see something like:
"Thu Mar 02 2017 16:44:02 GMT-0700 (MST)"
On SO, the console seems to use toISOString instead of the default toString, e.g.
var date = new Date(1488498242256);
// Standard output for the host environment
console.log(date);
// Call Date.prototype.toString specifically
console.log(date.toString());
If start and end are UTC times, then use moment.utc(start_time) and moment.utc(stop_time)
But it doesn't seem logical to compare UTC dates against a local date. That is what it looks like you are attempting.
I'm having trouble parsing dates for my website. It used to work fine on both IE and Chrome (I haven't tried Firefox yet). But recently I have been unable to parse dates on chrome.
The date string which I obtain from the database looks like this "Oct 17 2016 12:00AM"
Here is the code I'm using to debug my problem
console.log("String = "+item.DueDate);
console.log("new Date = " + new Date(item.DueDate));
console.log("Date Parse = " + Date.parse(item.DueDate));
console.log("Moment Parse = " + moment(item.DueDate));
Here is what is returned by IE:
String = Oct 17 2016 12:00AM
new Date = Mon Oct 17 2016 00:00:00 GMT-0400 (Eastern Daylight Time)
Date Parse = 1476676800000
Moment Parse = 1476676800000
And here is what is returned by Chrome:
String = Oct 17 2016 12:00AM
new Date = Invalid Date
Date Parse = NaN
Moment Parse = NaN
I use Date.parse() in one of my function that finds the difference between to dates:
function daydiff(first, second) {
return Math.round((second - first) / (1000 * 60 * 60 * 24));
}
var dif = daydiff(Date.parse(item.DueDate), Date.parse(item.DateShipped));
What should I do to my date string in order for it to work with both chrome and internet explorer?
Fixed
So I fixed it by changing my web api call to return a DateTime rather than string.
Never parse strings with the Date constructor (or Date.parse, they are equivalent for parsing) as it is almost entirely implementation dependent. Even the one format specified in ECMA-262 is not reliably parsed by all browsers in use.
Use a bespoke function or a library that provides parsing and formatting and always pass the format to parse to the parser. Suitable libraries are moment.js, date.js and fecha.js, but there are many others.
A bespoke function might look like:
function parseSpecia(s) {
var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
var h;
if (/a[mp]$/i.test(s)) {
h = /am$/i.test(s)? 0 : 12;
s = s.replace(/a[mp]$/i,'');
}
var b = s.split(/[ :]/)
return new Date(b[2], months[b[0].toLowerCase().substr(0,3)], b[1],(b[3]%12)+h, b[4]);
}
var s = 'Oct 17 2016 12:00AM';
console.log(parseSpecia(s));
Whereas using a library would look like:
fecha.parse('Oct 17 2016 12:00AM','MMM DD YYYY hh:mm:zz');
I have a string formatted as either
Today 3:28AM
Yesterday 3:28AM
08/22/2011 3:28AM
What I need to do is somehow extract into a variable the date portion of my string, ie. 'Today', 'Yesterday' or a date formatted as DD/MM/YYYY.
Is something like this possible at all with Javascript?
Since the JavaScript date parser won't recognize your dates, you can write a parser that puts the date into a format that it will recognize. Here is a function that takes the date examples that you gave and formats them to get a valid date string:
function strToDate(dateStr) {
var dayTimeSplit = dateStr.split(" ");
var day = dayTimeSplit[0];
var time = dayTimeSplit[1];
if (day == "Today") {
day = new Date();
} else if (day == "Yesterday") {
day = new Date();
day.setDate(day.getDate() - 1);
} else {
day = new Date(day);
}
var hourMinutes = time.substring(0, time.length -2);
var amPM = time.substring(time.length -2, time.length);
return new Date((day.getMonth() + 1) + "/" + day.getDate() + "/" + day.getFullYear()
+ " " + hourMinutes + " " + amPM);
}
Then you can call stroToDate to convert your date formats to a valid JavaScript Date:
console.log(strToDate("Today 3:28AM"));
console.log(strToDate("Yesterday 3:28AM"));
console.log(strToDate("08/22/2011 3:28AM"));
Outputs:
Sun Sep 25 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Sat Sep 24 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Mon Aug 22 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Obviously "Today" and "Yesterday" can never be transformed back to a real numeric date, for now it seems that what are you trying to do here is to save it as "Today" and "Yesterday", right?
It appears that the dd/mm/yyyy hh:mmxx you specified is always separated by a space.
so you can just split the string into two, and save the first part as your date.
the javascript function:
http://www.w3schools.com/jsref/jsref_split.asp
As for how to transform from "Today" back to 26/09/2011 etc, you need to seek solution from the XML side.
Here is a similar question: Javascript equivalent of php's strtotime()?
Here is the linked article: http://w3schools.com/jS/js_obj_date.asp
And the suggested solution:
Basically, you can use the date constructor to parse a date
var d=new Date("October 13, 1975 11:13:00");
There are a couple of ways you could do this. I will offer 2 of them.
option1:
If the day always at the beginning of the string you could capture the the first part by using a regular expression like /([a-z0-9]*)\s|([0-9]{1,})\/([0-9]{1,})\/([0-9]{1,})\s/ <- im not the best regex writer.
option2:
You could also do a positive look ahead if the time come immediately after the day (like your example above. Here is a link with the proper syntax for JS regex. http://www.javascriptkit.com/javatutors/redev2.shtml you can scroll down to lookaheads and see an example that should get you suared away there.
var reTYD = /(today|yesterday|\d{1,2}\/\d{1,2}\/\d{4})/i;
console.log( myString.match(reTYD) );