How to convert hours:minutes using javascript - javascript

I am currently working on Jvascript datetime part in that getting NaN error while converting hours and minutes to seconds like strtotime in PHP so I want to know how to convert minutes and seconds like the way we do in strtotime in PHP.
var d = new Date();
var total = d.getHours() + ":" + d.getMinutes();
var ts = Date.parse(total);
document.write(ts);
In output getting error NaN

This is a sort of inane question, but here's the number of seconds in the hours and minutes of that number:
var d = new Date();
var total = (d.getHours() * 60 * 60) + (d.getMinutes() * 60);
document.write(total);

First of all, Date.parse() takes a string of a specific format (such as Jul 18, 2018). Second, it will not convert the date to seconds, but will return the number of milliseconds since January 1, 1970 00:00:00 GMT.
If you need to convert hh:mm to seconds, the correct approach is to multiply the value of getHours() by 3600 and multiply the value of getMinutes() by 60, then sum up the two values.
var d = new Date();
var timeinsecs = d.getHours() * 3600 + d.getMinutes() * 60;
document.write(timeinsecs);
While if you need to get the time in seconds from January 1, 1970 00:00:00 GMT till the current time, you will need to parse the current date then divide by 1000:
var d = new Date();
document.write(Date.parse(d) / 1000);

Just get hours and minutes, then sum them multiplying hours * 3600 and minutes * 60, like this
var d = new Date();
var total = d.getHours() * 3600 + d.getMinutes() * 60;
document.write(total)

If you want to follow your original approach of not doing the math by hand, you need to include a date before the time (any date should do, could be today if you wish) and convert ms to seconds (both of these for the reasons Wais Kamal pointed out) as follows.
var d = new Date();
var total = d.getHours() + ":" + d.getMinutes();
var someDate ='July 4, 1776';//works, but maybe safer to choose since 1990
total=someDate+', '+total;
var ts = Date.parse(total);
document.write((ts- Date.parse(someDate))/1000);

Related

How to get 24:XX time from datetime?

Is there a DateTime Format that allows representation of the 24-hour clock to roll over where 24:XX is valid time?
For example
const secondsToTimeOfDay = (totalSeconds: number): string => {
return new Date(totalSeconds * 1000).toISOString().substr(11, 8);
};
var x = secondsToTimeOfDay(86399)
console.log(x)
Returns
23:59:59
But when seconds are greater than 86400 (The number of seconds in one day) it starts on the next day?
Example
var x = secondsToTimeOfDay(87000)
console.log(x)
Returns
00:10:00
Is there a date format that will return in a 24:xx format?
Example (I know this works but I want to know if it can be done using some kind of built-in Date Object)
const SomeNewFunction = (totalSeconds: number): string => {
var duration = 1000*totalSeconds
var milliseconds = parseInt((duration % 1000) / 100),
seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)));
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
}
var x = SomeNewFunction(87000)
var y = SomeNewFunction(97000)
console.log(x)
console.log(y)
Returns
24:10:00
26:56:40
Where the SomeNewFuntion uses some kind of DateTimeObject rather than math?
The JavaScript Date object represents a single instant in the history of the world, both date and time. While you can ignore the date part in display, it is always there - new Date(300000) doesn't represent "00:05:00 on any day", it represents "00:05:00 on January 1st 1970, according to UTC".
Since January 1st 1970 didn't have a 25th and 26th hour, the format you're asking for wouldn't make sense. Put a different way, "Feb 2nd 02:00" and "Feb 1st 26:00" are the same instant in time, but (if I understand your problem correctly) you want to be able to represent them distinctly.
There are time-related objects where "the 26th hour" would make sense:
A "duration", representing an absolute amount of time, independent of when it happens.
An "interval", representing the span of time between two specific instants.
A "time of day", in certain specialised cases, where you want to consider the "day" to last more than 24 hours for planning purposes.
JavaScript doesn't currently have any of those built-in, although there are libraries that do, and a proposal for adding them natively.
It's likely that most "time of day" implementations would not allow for more than 24 hours in the day, but you could represent it using a "duration" or "interval". The end result might look something like this:
var timetableEntry = {
"date": Temporal.PlainDate.from({year: 2006, month: 8, day: 24}),
"startOffsetFromMidnight": Temporal.Duration.from({ hours: 23, minutes: 30 }),
"endOffsetFromMidnight": Temporal.Duration.from({ hours: 26, minutes: 30 })
}
var journeyDuration = timetableEntry.endOffsetFromMidnight.subtract( timetableEntry.startOffsetFromMidnight );
var startDateTime = timetableEntry.date.add( timetableEntry.startOffsetFromMidnight );
var endDateTime = timetableEntry.date.add( timetableEntry.endOffsetFromMidnight);

How do I get the current timezone offset (and formatted it properly)?

How would I use javascript to format the computer's timezone offset to this format: <+/-><hourDiff>:<minuteDiff>, as in -7:00 (America/Los_Angeles) for example.
getTimezoneOffset returns a Number representing the time difference between UTC and Local Time, in minutes
var date = new Date();
var tzOffset = date.getTimezoneOffset();
var hours = ~~(tzOffset / 60);
var minutes = Math.abs(tzOffset % 60);
alert('Hours: ' + hours + ' Minutes: ' + minutes);

How to round down getTime result (ignoring minutes and hours)

I need to get the number of milliseconds of a certain day (even today), but need the result rounded down.
For example the number of milliseconds until this moment by using getTime() method is 1432738826994.
I would like to round this down to get the number of milliseconds until the beginning of the day, I need to get rid of all the minutes and hours. Is there a clean and simple way of achieving this?
If you are happy with using an external library, the easiest way is with moment.js.
moment().startOf('day').valueOf();
Will give you the unix epoch value for the beginning of today's date.
If you want to use the Javascript built in date object, then you would either need to set the hours, minutes, seconds and milliseconds to 0:
var rightNow = new Date();
rightNow.setHours(0);
rightNow.setMinutes(0);
rightNow.setSeconds(0);
rightNow.setMilliseconds(0);
Or create a new object from just the year, month and day values:
var rightNow = new Date();
var earlierToday = new Date(rightNow.getFullYear(), rightNow.getMonth(), rightNow.getDate(), 0, 0, 0, 0);
Pure javascript solution
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var mi = d.getMilliseconds();
var fromStart = mi + (s * 1000) + (m * 60 * 1000) + (h * 60 * 60 * 1000);
var roundedDown = Date.now() - fromStart;
To print the start of the day use new Date(Date.now() - fromStart)

Time difference in javascript

var time_1 = '13:44:25:912';
var time_2 = '14:45:30:910';
var inTime=time_1.split(":");
var outTime= time_2.split(":");
var hr = outTime[0] - inTime[0];
var min = ((outTime[1] - inTime[1])+hr*60)%60;
var sec = ((outTime[2] - inTime[2])+min*60)%60;
var milli = ((outTime[3] - inTime[3])+sec*1000)%1000;
document.write(milli);
document.write("<br>"+sec);
document.write("<br>"+min);
document.write("<br>"+hr);
Hey Friends I am need to find time difference in milliseconds I am able to get the difference in HH:MM:SS:Milli now i have convert all into milli plz help for the same
total milliseconds would be milli + (sec * 1000) + (min * 60000) + (hr * 3600000)
You can use the Date.parse function to get the number of milliseconds since January 1, 1970, 00:00:00 UTC. You need to pass a date-part to the string, but it doesn't really matter as long as you keep it the same in both strings.
JavaScript
var time1 = Date.parse("01 Jan 2000 13:44:25:912"),
time2 = Date.parse("01 Jan 2000 14:45:30:910");
console.log(time2 - time1);
Output
3664998
See jsFiddle

Check how many days between two dates (fails)

This is how I had it done:
var sDate = $('.start input').datepicker('getDate').getTime();
var nDate = $('.end input').datepicker('getDate').getTime();
var dias = Math.floor((nDate - sDate)/1000/60/60/24) + 1;
But it fails
20/03/2014 to 30/03/2014 -> 11 days
and
21/03/2014 to 31/03/2014 -> 10 days, when the difference is the same,
Where is the flaw?
The right code is this (as #vinod-gubbala stated above):
var dias = Math.round((nDate - sDate)/(1000*60*60*24));
Basically, you get the difference in (milliseconds) of the days and divide them by 1000 (to concert to seconds) * 60 (60 seconds per minute) * 60 (60 minutes per hour) * 24 (24 hours a day).
Don't know why you are adding +1 at the end. Of course this will work with complete days, I mean, comparing dates with he same time.
The problem you are experiencing could be something with the daylight saving time. Have in mind that for 2014, the last sunday of march (march 30th) there is a time change (at least in Europe), so there is an hour less and your function, as it do a floor, rounds down and you lose a day.
Regards.
You have to round instead of floor.
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var sDate = $('.start input').datepicker('getDate').getTime();
var nDate = $('.end input').datepicker('getDate').getTime();
var diffDays = Math.round(Math.abs((nDate - sDate)/(oneDay)));
Take a look at http://momentjs.com/
Your code will look like:
var a = moment($('.start input').datepicker('getDate').getTime());
var b = moment($('.end input').datepicker('getDate').getTime());
d = a.diff(b, 'days')
I did this:
var d1 = new Date('2013-03-20 00:00:00')
var d2 = new Date('2013-03-30 00:00:00')
(d2.getTime() - d1.getTime()) / 1000 / 60 / 60 / 24 + 1; //11
And then this:
var d1 = new Date('2013-03-21 00:00:00')
var d2 = new Date('2013-03-31 00:00:00')
(d2.getTime() - d1.getTime()) / 1000 / 60 / 60 / 24 + 1; //11
So there is no flaw there, most likely it's an error in creation of Date() object of the jQuery datepicker. I suggest you do the following:
console.log(nDate,sDate);
console.log(((nDate - sDate)/1000/60/60/24)+1);
And see what does that give you for both dates. You might spot an error there.

Categories

Resources