Related
I am using this code to display the current time on a site I'm building.
https://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock
Could someone tell me what code to add in order change the time to a different time zone? I'd also love the time to display 12 hour increments rather than 24.
Any help would be appreciated.
You can change the time zone by converting the time to UTC and adding the needed number of hours
var utc = today.getTime() + (today.getTimezoneOffset() * 60000);
var newDate = new Date(utc + (3600000 * -2));
As for converting to 12 hour format
var h = newDate.getHours() % 12;
function startTime(id, offset) {
var today = new Date();
var utc = today.getTime() + (today.getTimezoneOffset() * 60000);
var newDate = new Date(utc + (3600000 * -2));
var h = newDate.getHours() % 12;
var m = newDate.getMinutes();
var s = newDate.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="startTime();">
<div id="txt"></div>
</body>
</html>
edit
As mentioned by #BrockLee in a comment - as it is it will, indeed, show 12'o clock as 0. If this is not desired, you could change the line that sets the hours to, for example,
var h = (newDate.getHours() % 12 == 0) ? 12 : newDate.getHours() % 12;
In that example, you could use today.toLocaleTimeString() instead to show it in the preferred format of current user's locale.
Also, MDN's documentation on Date/Time related functionality in JavaScript will probably be much more helpful.
I have a date like this 2017-07-25 09:30:49, when I subtract 2017-07-25 10:30:00 and 2017-07-25 09:30:00, I need a result like 1 Hours.
I can't find correct search key for googling what I need.
Anyone know what should I search on google ? or someone knows some function about that?
PS. Mysql or Javascript
Try with date object in javascript
Like this
var d1 = new Date("2017-07-25 10:30:00");
var d2 = new Date("2017-07-25 09:30:49")
var diff = Math.abs(d1-d2); // difference in milliseconds
Then convert the milliseconds to hours
var hours = parseInt((diff/(1000*60*60))%24);
You can go through it
Get the time difference between two datetimes
But the query is not clear do you want only the hour difference or you want the difference converted to hour format
Like what it will give if 2017-07-25 09:30:49 and 2017-07-26 10:30:00 ? 25 hour or 1 hour?
here a code example of how to do it
var date1 = new Date("2017-07-25 09:30:49");
var date2 = new Date("2017-07-25 10:30:00");
var datesum = new Date(date1 - date2);
var hours = datesum.getHours();
var minutes = datesum.getMinutes();
var seconds = datesum.getSeconds();
console.log(hours + " hour, " + minutes + " minutes, " + seconds + " seconds" )
var dateString = "2017-07-25 09:30:49";
var dateString2= "2017-07-25 11:30:00";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateArray2= reggie.exec(dateString2);
var dateObject1= new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
var dateObject2= new Date(
(+dateArray2[1]),
(+dateArray2[2])-1, // Careful, month starts at 0!
(+dateArray2[3]),
(+dateArray2[4]),
(+dateArray2[5]),
(+dateArray2[6])
);
var diff = Math.abs(dateObject2-dateObject1); // difference in milliseconds
var hours = parseInt((diff/(1000*60*60))%24);
Try with the below dateFormatter function :
var d1 = new Date("2017-07-25 10:30:00");
var d2 = new Date("2017-07-25 09:30:00")
var diff = Math.abs(d1-d2);
var d = dateFormatter(diff);
console.log(d);
function dateFormatter(t){
var cd = 24 * 60 * 60 * 1000;
var ch = 60 * 60 * 1000;
var cm = 60*1000;
var d = Math.floor(t / cd);
var h = '0' + Math.floor( (t - d * cd) / ch);
var m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
var s = '0' + Math.round((t - (d * cd) - (h * ch) - (m * cm))/1000);
return d + " days, " + h.substr(-2) + " hours, " + m.substr(-2) + " minutes, " +s.substr(-2)+ " seconds";
}
I want to format date in ISO YYYY-MM-DDThh:mm:ss.sTZD format using javascript.
I can convert current date string in yyyy-MM-dd'T'HH:mm:ss.SSSZ format. For example 2016-01-11T02:40:33.117Z. But I want to get like 2016-01-11T02:40:33.117+1100.
Is it possible in javascript?
Try the following.
var date = new Date(Date.now());
date.setTime(date.getTime() - (date.getTimezoneOffset() * 60000));
var output = date.toISOString().substring(0, date.toISOString().length - 1) + ((date.getTimezoneOffset() / 60) < 0 ? "-" : "+") + ((Math.abs(date.getTimezoneOffset() / 60) < 10) ? ("0" + Math.abs(date.getTimezoneOffset() / 60)) : test) + "00";
The output variable should be close to what you are looking for. (the + and - may be inversed)
NOTE: There may exist a better solution; I will post it if I find it.
function getCurrentDateFormated() {
var date = new Date();
date.setTime(date.getTime() - (date.getTimezoneOffset() * 60000));
var timeZoneHours = date.getTimezoneOffset() / 60;
var finalHours = Math.abs(timeZoneHours) < 10 ?
timeZoneHours < 0 ? '-0' + timeZoneHours.toString().substring(1)
: '+0' + timeZoneHours.toString().substring(1)
: timeZoneHours;
var timeZoneMin = ((timeZoneHours - Math.floor(timeZoneHours)) * 60) < 10 ?
'0' + (timeZoneHours - Math.floor(timeZoneHours)) * 60 : (timeZoneHours - Math.floor(timeZoneHours)) * 60;
var timeZone = finalHours + timeZoneMin;
return date.toISOString().substring(0, 20) + date.getMilliseconds() + timeZone;
}
I have two HTML input boxes, that need to calculate the time difference in JavaScript onBlur (since I need it in real time) and insert the result to new input box.
Format example: 10:00 & 12:30 need to give me: 02:30
Thanks!
Here is one possible solution:
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}
DEMO: http://jsfiddle.net/KQQqp/
Try This
var dif = ( new Date("1970-1-1 " + end-time) - new Date("1970-1-1 " + start-time) ) / 1000 / 60 / 60;
tl;dr
One off run
const t1 = new Date(1579876543210) // your initial time
const t2 = new Date(1579987654321) // your later time
const diff = t2-t1
const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
const humanDiff = `${Math.floor(diff/HRS)}:${Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})}:${Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})}.${Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})}`
console.log("humanDiff:", humanDiff)
// > humanDiff: 30:51:51.0111
As a function
function humanDiff (t1, t2) {
const diff = Math.max(t1,t2) - Math.min(t1,t2)
const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
const hrs = Math.floor(diff/HRS)
const min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
const sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
const ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
return `${hrs}:${min}:${sec}.${ms}`
}
const t1 = new Date(1579876543210)
const t2 = new Date(1579987654321)
console.log("humanDiff(t1, t2):", humanDiff(t1, t2))
// > humanDiff: 30:51:51.0111
Explanation
Adjust humanDiff for your maximum and minimum reportable increments and formatting needs:
const t1 = new Date(1579876543210) // Set your initial time (`t1`)
const t2 = new Date(1579986654321) // , conclusion time (`t2`), and
const diff = t2-t1 // calculate their difference in milliseconds
console.log(" t2:", t2.toISOString()) // > t2: 2020-01-25T21:27:34.321Z
console.log(" t1:", t1.toISOString()) // > t1: 2020-01-24T14:35:43.210Z
console.log(" diff:", diff) // > diff: 111111111
// Set your constant time values for easy readability
const SEC = 1000
const MIN = 60 * SEC
const HRS = 60 * MIN
/* For a given unit
1) disregard any previously relevant units, e.g. to calculate minutes, we can
disregard all hours & focus on only the remainder - `(diff%HRS)`
2) divide the remainder by the given unit, e.g. for minutes, `(diff%HRS)/MIN`
3) disregard any remainder, e.g. again for minutes, `Math.floor((diff%HRS)/MIN)`
NOTE: for your maximum unit (HRS in the examples below) you probably _don't_
want to disregard high values, e.g. If the difference is >24 hrs and something,
you should either include a DAYS value, or simply display 30 hrs */
let hrs = Math.floor(diff/HRS)
let min = Math.floor((diff%HRS)/MIN)
let sec = Math.floor((diff%MIN)/SEC)
let ms = Math.floor(diff % SEC) // just the remainder
// BUT ms IS NOT ACTUALLY CORRECT, see humanDiff_3 for the fix ;-)
let humanDiff_1 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_1:", humanDiff_1)
// > humanDiff_1: 30:51:51.111
sec = Math.round((diff%MIN)/SEC) // can also just round the last unit
const humanDiff_2 = `${hrs} hrs ${min} mins & ${sec} secs`
console.log("humanDiff_2:", humanDiff_2)
// > humanDiff_2: 30 hrs 51 mins & 51 secs
/* To ensure a set number of digits, format the numbers with `toLocaleString`'s
`minimumIntegerDigits`, if more than 3 digits, also use its `useGrouping` */
hrs = Math.floor(diff/HRS)
min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
const humanDiff_3 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_3:", humanDiff_3)
// > humanDiff_3: 30:51:51.0111
// NOTE: milliseconds are now 4 digits
This solution works for calculating diff between to separate military times
Example format: start = 23:00 / end = 02:30
function diff(start, end) {
start = start.split(":");
end = end.split(":");
if(Number(start[0]) > Number(end[0]) ) {
var num = Number(start[0])
var countTo = Number(end[0]);
var count = 0;
for (var i = 1; num != countTo;) {
num = num + i
if(num > 24) {
num = 0
}
count++
}
var hours = count - 1;
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
if(startDate.getMinutes() > endDate.getMinutes()) {
var hours = count - 2;
var diff = 60 - (startDate.getMinutes() - endDate.getMinutes());
} else {
var diff = endDate.getMinutes() - startDate.getMinutes();
}
var minutes = diff
} else {
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
}
var returnValue = (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes
return returnValue;
}
Well this work almost great. Now use this code to calculate: 23:50 - 00:10 And see what you get.Or even 23:30 - 01:30. That's a mess.
Because getting the answer the other way in php is:
$date1 = strtotime($_POST['started']);
$date2 = strtotime($_POST['ended']);
$interval = $date2 - $date1;
$playedtime = $interval / 60;
But still, it works like yours.
I guess have to bring in the dates aswell?
And again: My hard research and development helped me.
if (isset($_POST['calculate'])) {
$d1 = $_POST['started'];
$d2 = $_POST['ended'];
if ($d2 < $d1) {
$date22 = date('Y-m-');
$date222 = date('d')-1;
$date2 = $date22."".$date222;
} else {
$date2 = date('Y-m-d');
}
$date1 = date('Y-m-d');
$start_time = strtotime($date2.' '.$d1);
$end_time = strtotime($date1.' '.$d2); // or use date('Y-m-d H:i:s') for current time
$playedtime = round(abs($start_time - $end_time) / 60,2);
}
And that's how you calculate time over to the next day.
//edit. First i had date1 jnd date2 switched. I need to -1 because this calculation only comes on next day and the first date vas yesterday.
After improving and a lot of brain power with my friend we came up to this:
$begin=mktime(substr($_GET["start"], 0,2),substr($_GET["start"], 2,2),0,1,2,2003);
$end=mktime(substr($_GET["end"], 0,2),substr($_GET["end"], 2,2),0,1,3,2003);
$outcome=($end-$begin)-date("Z");
$minutes=date("i",$outcome)+date("H",$outcome)*60; //Echo minutes only
$hours = date("H:i", $outcome); //Echo time in hours + minutes like 01:10 or something.
So you actually need only 4 lines of code to get your result. You can take only minutes or show full time (like difference is 02:32) 2 hours and 32 minutes.
What's most important: Still you can calculate overnight in 24 hour clock aka: Start time 11:50PM to let's say 01:00 AM (in 24 hour clock 23:50 - 01:00) because in 12 hour mode it works anyway.
What's most important: You don't have to format your input. You can use just plain 2300 as 23:00 input. This script will convert text field input to correct format by itself.
Last script uses standard html form with method="get" but you can convert it to use POST method as well.
This is an updated version of one that was already submitted. It is with the seconds.
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * (1000 * 60 * 60);
var minutes = Math.floor(diff / 1000 / 60);
diff -= minutes * (1000 * 60);
var seconds = Math.floor(diff / 1000);
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes + (seconds<= 9 ? "0" : "") + seconds;
}
My Updated Version:
Allows for you to convert the dates into milliseconds and go off of that instead of splitting.
Example Does -- Years/Months/Weeks/Days/Hours/Minutes/Seconds
Example: https://jsfiddle.net/jff7ncyk/308/
With seconds you provided is not get result to me please find my updated function giving you the correct seconds here - By Dinesh J
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1],start[2], 0);
var endDate = new Date(0, 0, 0, end[0], end[1],end[2], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
var seconds = Math.floor(diff / 1000)-120;
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes+ ":" + (seconds <= 9 ? "0" : "") + seconds;
}
Depending on what you allow to enter, this one will work. There may be some boundary issues if you want to allow 1am to 1pm
NOTE: This is NOT using a date objects or moment.js
function pad(num) {
return ("0"+num).slice(-2);
}
function diffTime(start,end) {
var s = start.split(":"), sMin = +s[1] + s[0]*60,
e = end.split(":"), eMin = +e[1] + e[0]*60,
diff = eMin-sMin;
if (diff<0) { sMin-=12*60; diff = eMin-sMin }
var h = Math.floor(diff / 60),
m = diff % 60;
return "" + pad(h) + ":" + pad(m);
}
document.getElementById('button').onclick=function() {
document.getElementById('delay').value=diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value
);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">
calTimeDifference(){
this.start = dailyattendance.InTime.split(":");
this.end = dailyattendance.OutTime.split(":");
var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
var time3 = ((time2 - time1) / 60);
var timeHr = parseInt(""+time3);
var timeMin = ((time2 - time1) % 60);
}
TimeCount = function()
{
t++;
var ms = t;
if (ms == 99)
{
s++;
t = 0;
if ( s == 60)
{
m++;
s = 0;
}
}
Dis_ms = checkTime(ms);
Dis_s = checkTime(s);
Dis_m = checkTime(m);
document.getElementById("time_val").innerHTML = Dis_m + ":" + Dis_s+ ":" + Dis_ms;
}
function checkTime(i)
{
if (i<10) {
i = "0" + i;
}
return i;
}
Try this: actually this a problem from codeeval.com
I solved it in this way .
This program takes a file as the argument so i used a little node js to read the file.
Here is my code.
var fs = require("fs");
fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
if (line !== "") {
var arr = line.split(" ");
var arr1 = arr[0].split(":");
var arr2 = arr[1].split(":");
var time1 = parseInt(arr1[0])*3600 + parseInt(arr1[1])*60 + parseInt(arr1[2]);
var time2 = parseInt(arr2[0])*3600 + parseInt(arr2[1])*60 + parseInt(arr2[2]);
var dif = Math.max(time1,time2) - Math.min(time1,time2);
var ans = [];
ans[0] = Math.floor(dif/3600);
if(ans[0]<10){ans[0] = "0"+ans[0]}
dif = dif%3600;
ans[1] = Math.floor(dif/60);
if(ans[1]<10){ans[1] = "0"+ans[1]}
ans[2] = dif%60;
if(ans[2]<10){ans[2] = "0"+ans[2]}
console.log(ans.join(":"));
}
});
We generally need time difference to estimate time taken by I/O operations, SP call etc, the simplest solution for NodeJs (the console is in callback- async execution) is following:
var startTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01
callYourExpectedFunction(param1, param2, function(err, result){
var endTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01
console.log(endTime - startTime)
//This will give you time taken in milliseconds by your function
if(err){
}
else{
}
})
It amazes me that JavaScript's Date object does not implement an add function of any kind.
I simply want a function that can do this:
var now = Date.now();
var fourHoursLater = now.addHours(4);
function Date.prototype.addHours(h) {
// How do I implement this?
}
I would simply like some pointers in a direction.
Do I need to do string parsing?
Can I use setTime?
How about milliseconds?
Like this:
new Date(milliseconds + 4*3600*1000 /* 4 hours in ms */)?
This seems really hackish though - and does it even work?
JavaScript itself has terrible Date/Time API's. Nonetheless, you can do this in pure JavaScript:
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
Test:
alert(new Date().addHours(4));
The below code will add 4 hours to a date (example, today's date):
var today = new Date();
today.setHours(today.getHours() + 4);
It will not cause an error if you try to add 4 to 23 (see the documentation):
If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly
It is probably better to make the addHours method immutable by returning a copy of the Date object rather than mutating its parameter.
Date.prototype.addHours= function(h){
var copiedDate = new Date(this.getTime());
copiedDate.setHours(copiedDate.getHours()+h);
return copiedDate;
}
This way you can chain a bunch of method calls without worrying about state.
The version suggested by kennebec will fail when changing to or from DST, since it is the hour number that is set.
this.setUTCHours(this.getUTCHours()+h);
will add h hours to this independent of time system peculiarities.
Jason Harwig's method works as well.
Get a date exactly two hours from now, in one line.
You need to pass milliseconds to new Date.
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
or
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
let nowDate = new Date();
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
console.log('now', nowDate);
console.log('expiry', expiryDate);
console.log('expiry 2', expiryDate2);
You can use the Moment.js library.
var moment = require('moment');
foo = new moment(something).add(10, 'm').toDate();
I also think the original object should not be modified. So to save future manpower here's a combined solution based on Jason Harwig's and Tahir Hasan answers:
Date.prototype.addHours= function(h){
var copiedDate = new Date();
copiedDate.setTime(this.getTime() + (h*60*60*1000));
return copiedDate;
}
If you would like to do it in a more functional way (immutability) I would return a new date object instead of modifying the existing and I wouldn't alter the prototype but create a standalone function. Here is the example:
//JS
function addHoursToDate(date, hours) {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
//TS
function addHoursToDate(date: Date, hours: number): Date {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
let myDate = new Date();
console.log(myDate)
console.log(addHoursToDate(myDate,2))
There is an add in the Datejs library.
And here are the JavaScript date methods. kennebec wisely mentioned getHours() and setHours();
Check if it’s not already defined. Otherwise, define it in the Date prototype:
if (!Date.prototype.addHours) {
Date.prototype.addHours = function(h) {
this.setHours(this.getHours() + h);
return this;
};
}
This is an easy way to get an incremented or decremented data value.
const date = new Date()
const inc = 1000 * 60 * 60 // an hour
const dec = (1000 * 60 * 60) * -1 // an hour
const _date = new Date(date)
return new Date(_date.getTime() + inc)
return new Date(_date.getTime() + dec)
Another way to handle this is to convert the date to unixtime (epoch), then add the equivalent in (milli)seconds, then convert it back. This way you can handle day and month transitions, like adding 4 hours to 21, which should result in the next day, 01:00.
SPRBRN is correct. In order to account for the beginning/end of the month and year, you need to convert to Epoch and back.
Here's how you do that:
var milliseconds = 0; //amount of time from current date/time
var sec = 0; //(+): future
var min = 0; //(-): past
var hours = 2;
var days = 0;
var startDate = new Date(); //start date in local time (we'll use current time as an example)
var time = startDate.getTime(); //convert to milliseconds since epoch
//add time difference
var newTime = time + milliseconds + (1000*sec) + (1000*60*min) + (1000*60*60*hrs) + (1000*60*60*24*days);
var newDate = new Date(newTime); //convert back to date; in this example: 2 hours from right now
Or do it in one line (where variable names are the same as above:
var newDate =
new Date(startDate.getTime() + millisecond +
1000 * (sec + 60 * (min + 60 * (hours + 24 * days))));
For a simple add/subtract hour/minute function in JavaScript, try this:
function getTime (addHour, addMin){
addHour = (addHour ? addHour : 0);
addMin = (addMin ? addMin : 0);
var time = new Date(new Date().getTime());
var AM = true;
var ndble = 0;
var hours, newHour, overHour, newMin, overMin;
// Change form 24 to 12 hour clock
if(time.getHours() >= 13){
hours = time.getHours() - 12;
AM = (hours>=12 ? true : false);
}else{
hours = time.getHours();
AM = (hours>=12 ? false : true);
}
// Get the current minutes
var minutes = time.getMinutes();
// Set minute
if((minutes + addMin) >= 60 || (minutes + addMin) < 0){
overMin = (minutes + addMin) % 60;
overHour = Math.floor((minutes + addMin - Math.abs(overMin))/60);
if(overMin < 0){
overMin = overMin + 60;
overHour = overHour-Math.floor(overMin/60);
}
newMin = String((overMin<10 ? '0' : '') + overMin);
addHour = addHour + overHour;
}else{
newMin = minutes + addMin;
newMin = String((newMin<10 ? '0' : '') + newMin);
}
// Set hour
if((hours + addHour >= 13) || (hours + addHour <= 0)){
overHour = (hours + addHour) % 12;
ndble = Math.floor(Math.abs((hours + addHour)/12));
if(overHour <= 0){
newHour = overHour + 12;
if(overHour == 0){
ndble++;
}
}else{
if(overHour == 0){
newHour = 12;
ndble++;
}else{
ndble++;
newHour = overHour;
}
}
newHour = (newHour<10 ? '0' : '') + String(newHour);
AM = ((ndble + 1) % 2 === 0) ? AM : !AM;
}else{
AM = (hours + addHour == 12 ? !AM : AM);
newHour = String((Number(hours) + addHour < 10 ? '0': '') + (hours + addHour));
}
var am = (AM) ? 'AM' : 'PM';
return new Array(newHour, newMin, am);
};
This can be used without parameters to get the current time:
getTime();
Or with parameters to get the time with the added minutes/hours:
getTime(1, 30); // Adds 1.5 hours to current time
getTime(2); // Adds 2 hours to current time
getTime(0, 120); // Same as above
Even negative time works:
getTime(-1, -30); // Subtracts 1.5 hours from current time
This function returns an array of:
array([Hour], [Minute], [Meridian])
If you need it as a string, for example:
var defaultTime: new Date().getHours() + 1 + ":" + new Date().getMinutes();
I think this should do the trick
var nextHour = Date.now() + 1000 * 60 * 60;
console.log(nextHour)
You can even format the date in desired format using the moment function after adding 2 hours.
var time = moment(new Date(new Date().setHours(new Date().getHours() + 2))).format("YYYY-MM-DD");
console.log(time);
A little messy, but it works!
Given a date format like this: 2019-04-03T15:58
//Get the start date.
var start = $("#start_date").val();
//Split the date and time.
var startarray = start.split("T");
var date = startarray[0];
var time = startarray[1];
//Split the hours and minutes.
var timearray = time.split(":");
var hour = timearray[0];
var minute = timearray[1];
//Add an hour to the hour.
hour++;
//$("#end_date").val = start;
$("#end_date").val(""+date+"T"+hour+":"+minute+"");
Your output would be: 2019-04-03T16:58
The easiest way to do it is:
var d = new Date();
d = new Date(d.setHours(d.getHours() + 2));
It will add 2 hours to the current time.
The value of d = Sat Jan 30 2021 23:41:43 GMT+0500 (Pakistan Standard Time).
The value of d after adding 2 hours = Sun Jan 31 2021 01:41:43 GMT+0500 (Pakistan Standard Time).