Reputation: 14145
If I have two times presented as strings like
14:10 and 19:02
how can I convert to Date object in order to get substracted value
var res = date1 - date2;
I tried to parse with
var date = new Date.parseExact(myDateVar, "HH:mm");
I'm getting
Uncaught TypeError: Date.parseExact is not a constructor
Upvotes: 8
Views: 20490
Reputation: 188
If you want it to be based of the current datetime. I found a pretty simple solution to this. Parse out the HH:MM to hours and minutes and then replace current ISO string with regex.
function toDateFromHoursAndMinutesString(time: string) {
const [hours, minutes] = time.split(':');
const currentDate = new Date();
const dateStringIso = currentDate.toISOString();
const replacedDateStringIso = dateStringIso.replace(/T.*/, `T${parseInt(hours)-1}:${minutes}:00.000Z`);
return new Date(replacedDateStringIso);
}
Upvotes: 0
Reputation: 146410
I would not recommend messing with dates and all their oddities (time zones, bad APIs, daylight saving time, leap seconds...). For instance, if you want to calculate "3:05" - "2:00"
and your script happens to run on the day there DST switch happens you may end up with results like 0:05
if you aren't carefull.
Fortunately, it's rather easy to parse a string with a time and convert it to a single unit that's easier to do maths with:
// Most error checking omitted for brevity
const text = "23:59";
const parsed = String(text).match(/^(?<minutes>\d+):(?<seconds>\d+)$/);
if (parsed !== null) {
const minutes = parseInt(parsed.groups.minutes, 10);
const seconds = parseInt(parsed.groups.seconds, 10);
const totalSeconds = 60 * minutes + seconds;
console.log(
"Input: %s; Minutes: %d; Seconds: %d; Total seconds: %d",
text, minutes, seconds, totalSeconds
);
}
You can calculate the difference between two times by calculating and then subtracting the corresponding totalSeconds
. If you wrap this in a custom function or object you'll have something reusable. For example:
// Most error checking omitted for brevity
function toSeconds(text) {
const parsed = String(text).match(/^(?<minutes>\d+):(?<seconds>\d+)$/);
if (parsed === null) {
return null;
}
return totalSeconds = 60 * parseInt(parsed.groups.minutes, 10) + parseInt(parsed.groups.seconds, 10);
}
function toMinutesSeconds(totalSeconds) {
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return String(minutes).padStart(2, "0") + ":" + String(seconds).padStart(2, "0");
}
const from = "14:10";
const to = "19:02";
const differenceInSeconds = toSeconds(to) - toSeconds(from);
console.log(
"Total seconds: %s; MM:SS: %s",
differenceInSeconds, toMinutesSeconds(differenceInSeconds)
);
It's also worth noting that, unlike date based solutions, this approach works with arbitrary durations (e.g. running time rather than time of the day).
Upvotes: 3
Reputation: 1202
You have several options:
var date1 = new Date(null, null, null, 14, 10);
var date2 = new Date(null, null, null, 19, 02);
And you will get real date objects.
var date1 = new Date('01/01/1970 14:10');
var date2 = new Date('01/01/1970 19:02');
And you will get same result.
Upvotes: 18
Reputation: 785
Off the top of my head:
var a="14:10";
var b="19:02";
var date1=new Date("01-01-2017 " + a + ":00");
var date2=new Date("01-01-2017 " + b + ":00");
//diff will be the number of milliseconds between the two times.
var diff = Math.abs(date1 - date2);
alert(diff);
of course this requires that you do its done within the same 24 hour period.
Upvotes: 2
Reputation: 43
I think new Date.parseExact is in C# so there is no constructor in javascript;
Upvotes: 0
Reputation: 1082
first convert this : 14:10 and 19:02
to date
var
pieces = "14:02".split(':')
minute, second;
if(pieces.length === 2) {
minute = parseInt(pieces[0], 10);
second = parseInt(pieces[1], 10);
}
and use this :
var date1 = new Date("7/13/2010");
var date2 = new Date("12/15/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
Upvotes: 0