In javascript, I want to get my local timezone offset such as -04:00 as a string. How can I do this?
Thanks
You can use Date object for this task.
let offset = new Date().getTimezoneOffset()
Now you got a string like -120 you can format as you like. You can divide by 60 to get hours and then use + or push:
offset = (offset / 60) + ":00";
one line:
new Date().getTimezoneOffset() / 60 + ":00";
Edit: Since you seem having problems, i made you a code example you can test.
<html>
<body>
<script>
let offset = new Date().getTimezoneOffset() / 60;
if (offset >= 0 && offset < 10) {
offset = "0" + offset;
} else if (offset > -10) {
offset = "-0" + offset.toString().substr(1);
} else {
offset = "00";
}
offset += ":00";
alert(offset);
</script>
</body>
</html>
I'm not handling 00:XX in case those exists.
I'd created a function...
function timezone(date=new Date()) {
var timezoneOffset=date.getTimezoneOffset();
var sign=(timezoneOffset<0)?"+":"-";
var minutes=Math.abs(timezoneOffset);
var hours=Math.floor(minutes/60);
minutes=minutes-60*hours;
return sign+("0"+hours).slice(-2)+":"+("0"+minutes).slice(-2);
}
You can pass a Date object, if you don't, one will be created.
timezoneOffset is in integer minutes: East of GMT = negative, West = positive.
sign is the opposite of the offset.
minutes abs = we've already got the sign, let's deal with absolute value.
hours - whole number of multiples of 60 minutes.
minutes - reminder of what it was minus 60 times whole hours. Could be done with %, it's a matter of preference.
return -
sign is a string: "+" or "-"
("0"+hours) is now a string: 7 becomes "07", 11 becomes "011", that's why:
.slice(-2) return the last 2 characters: "07" returns just that, "011" returns "11".
same for minutes.
and a ":" between.
You can test on different timezoneOffset values manually by replacing date.getTimezoneOffset() with a number.
Here's a possible solution:
const date = new Date()
const offset = date.getTimezoneOffset()
const sign = offset >= 0 ? '-' : '+'
const hours = Math.abs(offset / 60)
const minutes = Math.abs(offset % 60)
const hoursStr = `0${hours}`.slice(0, 2)
const minutesStr = `0${minutes}`.slice(0, 2)
console.log(`${sign}${hoursStr}:${minutesStr}`)
Note that not all timezones end at hours. Some countries use half hour timezones, like +03:30.
This seems to work...
function getTimeZoneOffset() {
var t = new Date().toString().match(/[-\+]\d{4}/)[0];
return t.substring(0,3) + ":" + t.substr(3);
}
Here's my solution. Rather then do your own division to get the hours, just use the functionality already in the date object:
const date = new Date();
const tzOffsetNumber = date.getTimezoneOffset();
const tzDate = new Date(0,0,0,0,Math.abs(tzOffsetNumber));
console.log(`${ tzOffsetNumber > 0 ? '-' : '+'}${tzDate.getHours()}:${("" + tzDate.getMinutes()).padStart(2,'0')}`)
Related
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).
I created a countdown, but it's returning a negative output instead of a positive one. I have researched reasons why this happens, but no luck. does anyone know why a countdown can return negative? and where in my code did I turned it negative?
thanks in advance!
var now = moment();
var targetDay = now.format("2020-11-03", "dddd, MMMM Do YYYY");
var countDown= Math.floor(moment().diff(targetDay, 'seconds'));
var Days, Minutes,Hours,Seconds;
setInterval(function(){
// Updating Days
Days =pad(Math.floor(countDown / 86400),2);
//updating Hours
Hours = pad(Math.floor((countDown - (Days * 86400)) / 3600),2);
// Updating Minutes
Minutes =pad(Math.floor((countDown - (Days * 86400) - (Hours * 3600)) / 60),2);
// Updating Seconds
Seconds = pad(Math.floor((countDown - (Days * 86400) - (Hours* 3600) - (Minutes * 60))), 2);
// Updation our HTML view
document.getElementById("days").innerHTML=Days + ' Days';
document.getElementById("hours").innerHTML=Hours + ' Hours';
document.getElementById("minutes").innerHTML=Minutes+ ' Minutes';
document.getElementById("seconds").innerHTML=Seconds + ' Seconds';
// Decrement
countDown--;
if(countDown === 0){
countDown= Math.floor(moment().diff(targetDay, 'seconds'));
}
},1000);
// Function for padding the seconds i.e limit it only to 2 digits
function pad(num, size) {
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
Quote from momentjs docs:
By default, moment#diff will return a number rounded towards zero
(down for positive, up for negative)
If the moment is earlier than the moment you are passing to
moment.fn.diff, the return value will be negative.
So, to fix this issue you should use the following code
var now = moment();
var targetDay = moment('2020-11-23', 'YYYY-MM-DD');
var countDown= Math.floor(targetDay.diff(now, 'seconds'));
Value will be positive because targetDay moment is later that the moment you're passing to moment.diff
I'm working on a web timesheet where users use timepicker to determine start & end times and I'd like to have the form automatically find the difference between the two times and place it in a 3rd input box. I understand that I need to get the values, convert them to milliseconds, then subtract the first number from the second, convert the difference back to human time and display that in the third box. But I can't seem to wrap my head around time conversion in javascript. Here's what I have so far:
function date1math(){
var date1in = document.getElementById("date-1-in").value;
var date1out = document.getElementById("date-1-out").value;
date1in = date1in.split(":");
date1out = date1out.split(":");
var date1inDate = new Date(0, 0, 0, date1in[0], date1in[1], 0);
var date1outDate = new Date(0, 0, 0, date1out[0], date1out[1], 0);
var date1math = date1outDate.getTime() - date1inDate.getTime();
var hours = Math.floor(date1math / 1000 / 60 / 60);
date1math -= hours * 1000 * 60 * 60;
var minutes = Math.floor(date1math / 1000 / 60);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
document.getElementById("date-1-subtotal").value = date1math(date1in, date1out);
}
I want to take the timepicker result (say 9:00am) from the input date-1-in, the timepicker result (say 5:00pm) from the input date-1-out, and then place the difference as a number in date-1-subtotal.
Presumably the input is a string in the format hh:mm (e.g. 09:54) and that the two strings represent a time on the same day. You don't mention whether an am/pm suffix is included, but it's there in the text so I'll assume it might be.
If daylight saving changes can be ignored, the simplest method is to convert the string to minutes, find the difference, then convert back to hours and minutes, e.g.:
// Convert hh:mm[am/pm] to minutes
function timeStringToMins(s) {
s = s.split(':');
s[0] = /m$/i.test(s[1]) && s[0] == 12? 0 : s[0];
return s[0]*60 + parseInt(s[1]) + (/pm$/i.test(s[1])? 720 : 0);
}
// Return difference between two times in hh:mm[am/pm] format as hh:mm
function getTimeDifference(t0, t1) {
// Small helper function to padd single digits
function z(n){return (n<10?'0':'') + n;}
// Get difference in minutes
var diff = timeStringToMins(t1) - timeStringToMins(t0);
// Format difference as hh:mm and return
return z(diff/60 | 0) + ':' + z(diff % 60);
}
var t0 = '09:15am';
var t1 = '05:00pm';
console.log(getTimeDifference('09:15am', '05:00pm')); // 07:45
console.log(getTimeDifference('09:15', '17:00')); // 07:45
If daylight saving is to be incorporated, you'll need to include the date so that date objects can be created and used for the time difference. The above can use either 12 or 24 hr time format.
I am trying to compare two dates in javascript, which are in two input type="text", and that have the format "06/11/2013 13:24".
Any idea of how to compare them?
Thanks!
You need to parse string to Date - object:
var firstDate = new Date("06/11/2013 13:24");
var secondDate = new Date(youSecondDateString);
Age from Date of Birth using JQuery
Possibly a duplicate question to above but the answers is
var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;
if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
//perform desired operation here
}
The Date object will do what you want - construct one for each date, then just compare them using the usual operators.
For example, subtracting date1 from date2 will give you the number of milliseconds between two dates.
You can get the number of seconds by dividing the milliseconds by 1000, and rounding the number:
var seconds = Math.round((date2-date1)/1000);
You could then divide by 60 to get the minutes, again by 60 to get the hours, then by 24 to get the days (and so on).
Here's how you might get a figure in the format dd:hh:mm
window.minutesPerDay = 60 * 24;
function pad(number) {
var result = "" + number;
if (result.length < 2) {
result = "0" + result;
}
return result;
}
function millisToDaysHoursMinutes(millis) {
var seconds = millis / 1000;
var totalMinutes = seconds / 60;
var days = totalMinutes / minutesPerDay;
totalMinutes -= minutesPerDay * days;
var hours = totalMinutes / 60;
totalMinutes -= hours * 60;
return days + ":" + pad(hours) + ":" + pad(totalMinutes);
}
var date1 = new Date("06/11/2013 13:24"),
date2 = new Date("07/11/2013 13:24"),
milliseconds = date2 - date1;
alert(millisToDaysHoursMinutes(milliseconds));
Fiddle
I took the millisToDaysHoursMinutes function from here.
I have two fields in my form where users select an input time (start_time, end_time) I would like to, on the change of these fields, recalcuate the value for another field.
What I would like to do is get the amount of hours between 2 times. So for instance if I have a start_time of 5:30 and an end time of 7:50, I would like to put the result 2:33 into another field.
My inputted form times are in the format HH:MM:SS
So far I have tried...
$('#start_time,#end_time').on('change',function()
{
var start_time = $('#start_time').val();
var end_time = $('#end_time').val();
var diff = new Date(end_time) - new Date( start_time);
$('#setup_hours').val(diff);
try
var diff = ( new Date("1970-1-1 " + end_time) - new Date("1970-1-1 " + start_time) ) / 1000 / 60 / 60;
have a fiddle
It depends on what format you want your output in. When doing math with Date objects, it converts them into milliseconds since Epoch time (January 1, 1970, 00:00:00 UTC). By subtracting the two (and taking absolute value if you don't know which is greater) you get the raw number of milliseconds between the two.
From there, you can convert it into whatever format you want. To get the number of seconds, just divide that number by 1000. To get hours, minutes, and seconds:
var diff = Math.abs(new Date(end_time) - new Date(start_time));
var seconds = Math.floor(diff/1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds/60);
seconds = seconds % 60;
var hours = Math.floor(minutes/60);
minutes = minutes % 60;
alert("Diff = " + hours + ":" + minutes + ":" + seconds);
You could of course make this smarter with some conditionals, but this is just to show you that using math you can format it in whatever form you want. Just keep in mind that a Date object always has a date, not just a time, so you can store this in a Date object but if it is greater than 24 hours you will end up with information not really representing a "distance" between the two.
var start = '5:30';
var end = '7:50';
s = start.split(':');
e = end.split(':');
min = e[1]-s[1];
hour_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
}
hour = e[0]-s[0]-hour_carry;
min = ((min/60)*100).toString()
diff = hour + ":" + min.substring(0,2);
alert(diff);
try this :
var diff = new Date("Aug 08 2012 9:30") - new Date("Aug 08 2012 5:30");
diff_time = diff/(60*60*1000);