It seems that JavaScript's Date() function can only return local date and time. Is there anyway to get time for a specific time zone, e.g., GMT-9?
Combining #Esailija and #D3mon-1stVFW, I figured it out: you need to have two time zone offset, one for local time and one for destination time, here is the working code:
var today = new Date();
var localoffset = -(today.getTimezoneOffset()/60);
var destoffset = -4;
var offset = destoffset-localoffset;
var d = new Date( new Date().getTime() + offset * 3600 * 1000)
An example is here: http://jsfiddle.net/BBzyN/3/
var offset = -8;
new Date( new Date().getTime() + offset * 3600 * 1000).toUTCString().replace( / GMT$/, "" )
"Wed, 20 Jun 2012 08:55:20"
<script>
var offset = -8;
document.write(
new Date(
new Date().getTime() + offset * 3600 * 1000
).toUTCString().replace( / GMT$/, "" )
);
</script>
You can do this in one line:
let d = new Date(new Date().toLocaleString("en-US", {timeZone: "timezone id"})); // timezone ex: Asia/Jerusalem
var today = new Date();
var offset = -(today.getTimezoneOffset()/60);
You can always get GMT time (so long as the client's clock is correct).
To display a date in an arbitrary time-zone, construct a string from the UTC hours, minutes, and seconds after adding the offset.
There is simple library for working on timezones easily called TimezoneJS can be found at https://github.com/mde/timezone-js.
Related
I want to get Unix timestamp (time in seconds) from tomorrow.
I have tried the following with no success:
var d = new Date();
d.setDate(d.getDay() - 1);
d.setHours(0, 0, 0);
d.setMilliseconds(0);
console.log(d/1000|0)
How would I fix the above?
Just modified your code and it works fine
var d = new Date();
d.setDate(d.getDate() + 1);
d.setHours(0, 0, 0);
d.setMilliseconds(0);
console.log(d)
>> Sun Apr 21 2019 00:00:00 GMT+0530 (India Standard Time)
Hope this will work for you
This should do it.
Copied directly from https://javascript.info/task/get-seconds-to-tomorrow
function getSecondsToTomorrow() {
let now = new Date();
// tomorrow date
let tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1);
let diff = tomorrow - now; // difference in ms
return Math.round(diff / 1000); // convert to seconds
}
console.log(getSecondsToTomorrow());
you could use a third party library like moment js which makes your life alot easier
momentjs
You can use a unix timestamp and add 24*60*60*1000 (same as 86400000) to the current time's timestamp. You can then pass that to new Date() like this:
24 = hours
60 = minutes
60 = seconds
1000 = converts the result to milliseconds
// Current timestamp
const now = Date.now()
// Get 24 hours from now
const next = new Date(now + (24*60*60*1000))
// Create tomorrow's date
const t = new Date(next.getFullYear(), next.getMonth(), next.getDate())
// Subtract the two and divide by 1000
console.log(Math.round((t.getTime() - now) / 1000), 'seconds until tomorrow')
I have a mySQL database in which I store the time in this format automatically:
2015-08-17 21:31:06
I am able to retrieve this time stamp from my database and bring it into javascript. I want to then get the current date time in javascript and determine how many days are between the current date time and the date time I pulled from the database.
I found this function when researching how to get the current date time in javascript:
Date();
But it seems to return the date in this format:
Tue Aug 18 2015 10:49:06 GMT-0700 (Pacific Daylight Time)
There has to be an easier way of doing this other than going character by character and picking it out from both?
You can build a new date in javascript by passing the data you receive from your backend as the first argument.
You have to make sure that the format is an accepted one. In your case we need to replace the space with a T. You may also be able to change the format from the back end.
Some good examples are available in the MDN docs.
var d = new Date("2015-08-17T21:31:06");
console.log(d.getMonth());
To calculate the difference in days you could do something like this:
var now = new Date();
var then = new Date("2015-08-15T21:31:06");
console.log((now - then)/1000/60/60/24);
You can select the difference directly in your query:
SELECT DATEDIFF(now(), myDateCol) FROM myTable;
the Date object has a function called getTime(), which will give you the current timestamp in milliseconds. You can then get the diff and convert to days by dividing by (1000 * 3600 * 24)
e.g.
var date1 = new Date()
var date2 = new Date()
var diffInMs = date2.getTime() - date1.getTime()
var diffInDays = diffInMs/(1000*3600*24)
Since none of the other answer got it quite right:
var pieces = "2015-08-17 21:31:06".split(' ');
var date = pieces[0].split('-');
var time = pieces[1].split(':');
var yr = date[0], mon = date[1], day = date[2];
var hour = time[0], min = time[1], sec = time[2];
var dateObj = new Date(yr, mon, day, hr, min, sec);
//if you want the fractional part, omit the call to Math.floor()
var diff = Math.floor((Date.now() - dateObj.getTime()) / (1000 * 60 * 60 * 24));
Note that none of this deals with the timezone difference between the browser and whatever you have stored in the DB. Here's an offset example:
var tzOff = new Date().getTimezoneOffset() * 60 * 1000; //in ms
Can someone explain how to add the UTC offset to getUTCHours so that it returns the correct hours? I know that it is currently 9:36pm MST. We currently are on Daylight saving time so we have a UTC offset of -6. So I would expect that if I add the offset to getUTCHours then I should get 21. Instead I get -2. What am I doing wrong?
var offset=-6;
var dt = new Date();
var h=dt.getUTCHours();
var hour=h+offset;
console.log(hour);
It's the 29th in UTC time so the hours are only 4. Compare the getDate vs the getUTCDate of your date object - if they are different increment your hours by 24.
var offset=-6;
var dt = new Date();
var h=dt.getUTCHours();
var hour=h+offset;
if(dt.getDate()!=dt.getUTCDate()){
hours+=24;
}
console.log(hour);
Not exactly sure on why you are doing this, just a hint:
var dt = new Date(2015,0,1,21,30);
var ltm = ( dt.getUTCHours()*60 ) - dt.getTimezoneOffset();
var localTimeString = Math.floor(ltm / 60) + ":" + (ltm % 60);//21:30
$(document).ready(function() {
var date = new Date();
var data_new = [];var url ='http://www.domain.com /kjdshlka/api.php?date=2014-07-15';
$.getJSON(url,function(result) {
var elt = [date,result.requests];data_new.push(elt);console.log(data_new);
});
});
I am struggling to decrement the date by one day using javascript for loop.Here is my code,from the url im getting some requests.like if i decrease the date by one day other requests will come .Now i need this process for 7days using javascript for loop.Can anybody please tel me how to do ?
var date = new Date(); // Date you want, here I got the current date and time
date.setDate(date.getDate()-1);
getDate() will give you the date, then reduce it by 1 and using setDate() you can replace date again.
var today = new Date();
var yesterday = new Date(today.getTime() - (24 * 60 * 60 * 1000)); //(hours * minutes * seconds * milliseconds)
console.log(yesterday);
var now = new Date();
console.log(now);
var yesterday = new Date(now - 86400000);
console.log(yesterday);
/* In a Decrement Loop*/
for(var i=100;i>0;i--){
console.log(new Date(now - i*86400000));
}
I apologize if this question has been asked already but I couldn't find it for my problem.
I have seen this but am not sure what the number it returns represents: Date() * 1 * 10 * 1000
I'd like to set a future moment in time, and then compare it to the current instance of Date() to see which is greater. It could be a few seconds, a few minutes, a few hours or a few days in the future.
Here is the code that I have:
var futureMoment = new Date() * 1 *10 * 1000;
console.log('futureMoment = ' + futureMoment);
var currentMoment = new Date();
console.log('currentMoment = ' + currentMoment);
if ( currentMoment < futureMoment) {
console.log('currentMoment is less than futureMoment. item IS NOT expired yet');
}
else {
console.log('currentMoment is MORE than futureMoment. item IS expired');
}
Javascript date is based on the number of milliseconds since the Epoch (1 Jan 1970 00:00:00 UTC).
Therefore, to calculate a future date you add milliseconds.
var d = new Date();
var msecSinceEpoch = d.getTime(); // date now
var day = 24 * 60 * 60 * 1000; // 24hr * 60min * 60sec * 1000msec
var futureDate = new Date(msecSinceEpoc + day);
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var futureMoment = new Date() * 1 *10 * 1000;
becomes
var now = new Date();
var futureMoment = new Date(now.getTime() + 1 *10 * 1000);
I think you mean to add time. Not multiply it.
If you deal with time, there is a lot of tools to choose.
Try moment library.
Used following code to compare selected date time with current date time
var dt = "Thu Feb 04 2016 13:20:02 GMT+0530 (India Standard Time)"; //this date format will receive from input type "date"..
function compareIsPastDate(dt) {
var currDtObj = new Date();
var currentTime = currDtObj.getTime();
var enterDtObj = new Date(dt);
var enteredTime = enterDtObj.getTime();
return (currentTime > enteredTime);
}