Reputation: 643
Suppose I have this time
'2018-08-03T15:53:57.000Z'
I need to convert only the time part to milliseconds
I tried this but didn't work and throws error
moment.utc("2018-08-03T15:53:57.000Z").format('HH:mm:ss').milliseconds()
Error
TypeError: (0 , _moment2.default)(...).format(...).milliseconds is not a function
Can someone please help how can I convert only time to millisecond?
Thank you!!!
Upvotes: 4
Views: 7277
Reputation: 10864
Simply do this if you want to get the milliseconds:
const ms = moment.utc("2018-08-03T15:53:57.000Z").valueOf()
Edit: The above is how you could do it in moment since you specifically said "using Moment".
You could also use plain JS without using a library as follows:
const date = new Date("2018-08-03T15:53:57.000Z");
.valueOf()
date.valueOf() // 1533311637000
.getTime()
date.getTime() // 1533311637000
Upvotes: 6
Reputation: 13059
No need to use moment to do this. The date string can be parsed sufficiently by vanilla JS.
let date = new Date('2018-08-03T15:53:57.000Z');
And to get the timestamp (in milliseconds) of this date;
let millis = date.getTime();
And, since there are 86400 seconds in a day (24*60*60) there are 86,400,000 milliseconds and we can use the remainder after division by this number to get the number of milliseconds the time portion represents. Following is the statement:
let millisToday = millis % 86400000;
UPDATE
Now using getTime()
instead of valueOf()
as it is the "proper" way to get the timestamp of the Date object.
Upvotes: 1
Reputation: 39270
I'll add my answer in case I got it wrong then someone can comment.
If I send new Date().toISOString()
to someone in a different time zone then the time will differ for this person. If I ask that person to have a skype call at 13:00 their time it could mean it's 18:00 my local time.
So if the person sending me the date string is from the UK and sends me ...T13:00.000Z
That actually means 18:00 for me.
Here is how you can correctly get the time in milliseconds from your midnight of the date converted to your local time:
const date = new Date(2007, 1, 1, 0, 0, 2).toISOString();
console.log('date:',date);
console.log('date in your local time:',new Date(date).toString());
const millisecondsFromMidNight = (date) => {
var dateObject = new Date(date);
return (
dateObject.getTime() -
new Date(
dateObject.getFullYear(),
dateObject.getMonth(),
dateObject.getDate(),
0,
0,
0,
0,
).getTime()
);
};
console.log(millisecondsFromMidNight(date));
Example where DST goes in effect:
var minutesFromMidnight = (date) => {
var dateObject = new Date(date);
console.log('date:', date);
console.log(
'date in your local time:',
dateObject.toString(),
);
return (
dateObject.getTime() -
new Date(
dateObject.getFullYear(),
dateObject.getMonth(),
dateObject.getDate(),
0,
0,
0,
0,
).getTime()
);
};
console.log(
minutesFromMidnight('2018-10-28T00:59:00.000Z') / 60000,
);
console.log(
minutesFromMidnight('2018-10-28T01:01:00.000Z') / 60000,
);
Upvotes: 1