Comparing date time with current datetime - javascript

From server I am getting a date time like this format "Thu, 02-Jan-2020 08:32:18 GMT" and I want to compare it current GMT date time . How I will do that in javascript.

const serverDate = new Date('Thu, 02-Jan-2020 08:32:18 GMT');
const clientDate = new Date();
const clientOffset = clientDate.getTimezoneOffset() * 60 * 1000; // get milliseconds from minutes
if (serverDate.getTime() > clientDate.getTime() + clientOffset) {
console.log('serverDate is later than clientDate');
} else {
console.log('serverDate is earlier than clientDate');
}
Here we are using built-in Date objects. getTime() method from this example is used to get the number of milliseconds passed since January 1st, 1970. This way we ended up just comparing 2 numbers.
If you set different timezone on a client device than GMT+0 on the server, getTimezoneOffset() comes to help. It returns the number of minutes we need to add to the getTime() result so that the client timestamp will also be in GMT+0 timezone.

I would suggest using moment.js. Using it is as simple as for example x.isSameAs(y), x.isBefore(y) x.isAfter(y)

Related

Date in Javascript countdown

I am trying to make countdown for website. I have simple javascript code as below. Last line in code gives output 5 where it should give output zero as I have not assigned any hour value to it. And as a result my countdown stops 5 hours late then exact time I want it to stop.
var date1 = new Date("2019-12-09");
document.write(date1.getHours());
You can use getTimezoneOffset() and then subtract it off:
var date1 = new Date("2019-12-09");
console.log(date1.getHours() + date1.getTimezoneOffset() / 60);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
The problem here is that when you create the Date without specifying the timezone, it will treat it as if the hours/minutes/seconds were set to zero and then the whole date was converted to your local timezone (timezone of the browser to be specific). Depending on where you are in the world, it can be many hours off the mark. Because of that, every time you need to compare two dates (either for countown or anything else), you have to either use UTC methods or make sure you specify the timezone on both dates explicitly:
const timeZero = new Date('01 Jan 1970 00:00:00 GMT') // <<- explicit GMT timezone
const isoTimeZero = new Date('1970-01-01T00:00:00.000Z') // ISO format of the same
...
const today = new Date();
const utcDateStr = `${today.getUTCFullYear()}-${today.getUTCMonth()+1}-${today.getUTCDate()} 00:00:00.000 GMT`
const utcDate = new Date(utcDateStr)
const offsetInMillisec = utcDate - timeZero // You can calculate hours/munites left to zero as needed
This example ignores hours/minutes/seconds - they are easy to add in the same fashion as the date. The key is to always use the same timezone for both days, preferably UTC
Alternatively, you may want to consider switching to moment.js and saving yourself lots of hassle :)

UTC time from new Date() using JS

I have checked so many places but could not find a proper answer. I have to get current time in UTC and then subtract few days (say 2 days). So if today is 25th March, I would like to get data of past 2 days starting from 23rd March 00:00 hours GMT.
I can get individual hours and minutes in GMT. But the moment I do new Date() it gives me in local timestamp. Normally I would subtract the current GMT hours and minutes from current time and the number of days I have to subtract.
But when I do a new Date() instead of GMT I get local time. I can do toUTCString() but that is after getting the time in my local time format. If I subtract my local time too then my code won't work universally.
So I need to get the new Date() function in UTC format. I checked a lot of places but nothing seems to work.
The getTime method will return a number representing the milliseconds elapsed from the epoch (1 January 1970 00:00:00 UTC). This method always uses UTC for time representation.
Then you could subtract 2 days and get another Date instance:
var timestamp = new Date().getTime();
timestamp = timestamp - 2 * 24 * 60 * 60 * 1000;
var newDate = new Date(timestamp);
I recommend you use Moment.js to operate with Dates.
In particular adding or subtracting dates is very easy using this library, for example:
moment().subtract(2, 'days')
If you want to do it natively, there are many ways to do it, but one of them is this:
const d = new Date();
d.setDate(d.getDate() - 2);
About UTC date:
But the moment I do new Date() it gives me in local timestamp
That's just a string representation, that is different depending on the environment. Dates are stored internally in UTC, so there is no problem using new Date() and operating with it.

JS date calculation with UTC stored on server?

I'm passing back a UTC date from the server, and I need some JS to find the difference in seconds between "now" and the date passed back from the server.
I'm currently trying moment, with something like
var lastUpdatedDate = moment(utcStringFromServer);
var currentDate = moment();
var diff = currentDate - lastUpdatedDate;
problem is, this gives a very invalid answer, because UTC is coming down from the server, and creating a new moment() makes it local. How can I do a calculation with respect to full UTC so it's agnostic of any local timing?
What you aren't quite understanding is that Dates are stored as the number of milliseconds since midnight, Jan 1, 1970 in UTC time. When determining the date/time in the local timezone of the browser, it first works out what the date/time would be in UTC time, then adds/subtracts the local timezone offset.
When you turn a Date back into a number, using +dateVar or dateVar.valueOf() or similar, it is back to the number of milliseconds since 01/01/1970T00:00:00Z.
The nice part about this is that whenever you serialise dates in UTC (either as a number, or as ISO String format), when it gets automatically converted to local time by Javascript's Date object, it is exactly the same point in time as the original value, just represented in local time.
So in your case, when you convert a local date to a number, you get a value of milliseconds in UTC that you are subtracting a value in milliseconds in UTC from. The result will be the number of milliseconds that has passed between the time from the server and the time the new Date() call is made.
Where it gets tricky is when you want a timestamp from the server to not be translated to local time, because you want to show the hours and minutes the same regardless of timezone. But that is not what you need in this case.
Try this way hope it may help:
var lastUpdatedDate = moment(utcStringFromServer);
var date = Date.UTC();
var currentDate = moment(date);
var diff = currentDate - lastUpdatedDate;
I'm assuming that utcStringFromServer is something like this:
Fri, 19 Aug 2016 04:27:27 GMT
If that's the case, you don't really need Moment.js at all. If you pass that string to Date.parse(), it'll return the number of milliseconds since Jan. 1, 1970. You can then use the .toISOString() method to get the same info about right now (converted to UTC) and parse it the same way to get milliseconds since 1970. Then, you can subtract the former from the latter and divide it by 1000 to convert back to seconds.
All in all, it would look something like this:
var lastUpdatedDate = Date.parse(utcStringFromServer);
var currentDate = Date.parse((new Date()).toISOString())
var diff = (currentDate - lastUpdatedDate) / 1000.0; // Convert from milliseconds

javascript date from php unix timestamp

In database i have a row with date & time, say 2014-04-16 00:00:00 then I convert that datetime to unix timestamp using
strtotime('2014-04-16 00:00:00') * 1000; // result 1397577600000
In javascript i am trying to get the hour using the following code
var d = new Date(1397577600000); // 1397577600000 from php unix timestamp in previous code
d.getHours(); // return 23
d.getMinutes(); // return 0
why getHours() return 23 instead of 0? is there any difference between js timestamp and php timestamp?
Date objects in javascript will always return values based on the browser's current timezone. So if d.getHours() is returning 23 for you, that would suggest your local browser timezone is one hour earlier than UTC (-01:00).
It you want the hours for a Date object based on UTC timezone, you can use:
d.getUTCHours()
Follow Up:
Just to throw out some free advice, you could use the following code to deal with your date values from one context to another:
PHP:
// Fetched from the db somehow
$datetime_db = '2014-04-16 00:00:00';
// Convert to PHP DateTime object:
$datetime_obj = new DateTime($datetime_db, new DateTimeZone('UTC'));
// Format DateTime object to javascript-friendly ISO-8601 format:
$datetime_iso = $datetime_obj->format(DateTime::W3C);
Javascript:
var d = new Date('2014-04-16T00:00:00+00:00'); // 2014-04-16T00:00:00+00:00 from PHP in previous code
d.getUTCHours(); // returns 0
This keeps the datetime variables in a language-specific object format when being handled in that language, and serializes the value into a string format that all current browsers/languages accept (the international standard ISO-8601).
I am getting 21 here because in Javascript local timezone of the user will be considered to fetch time and date.
Ok, based on what Arun P Johnny said.
I change the strtotime parameter to match my timezone, in this case i changed it to
strtotime('2014-04-16 00:00:00 GMT+7') * 1000;
hope this help anybody that have the same problem as I.

Convert Javascript Date object to PST time zone

I need to pick a future date from calender, suppose the date I am selecting is 10/14/2014, now what I want is to send the date with the time to server, so that at server end it always reaches as 6am time in PST timezone and the format of date should be UTC.
What I am doing is
targetDate = new Date($("#calendar").val());
targetDate = targetDate.toUTCString();
targetDate = targetDate.addHours(14);
My understanding is that PST timezone is -8:00 so I have added 14 hours to the UTC time so that time becomes 6:00am PST
The problem I am facing is that it is not letting me to add 14 hours since the object has already been converted to string.
addHours is the custom function I am having to add the hours in given time.
If I write
targetDate = new Date($("#calendar").val());
targetDate = targetDate.addHours(14);
targetDate = targetDate.toUTCString();
then it works good but in this case problem is time will always be different when the request is coming from different timezones.
Any help is appreciated.
This worked for me:
var myDate = new Date(1633071599000)
var pstDate = myDate.toLocaleString("en-US", {
timeZone: "America/Los_Angeles"
})
console.log(pstDate)
Which outputs "9/30/2021, 11:59:59 PM"
You said:
My understanding is that PST timezone is -8:00 so I have added 14 hours to the UTC time so that time becomes 6:00am PST
Uh - no. That will put you on the following day. If you wanted to stay in PST, you would subtract 8 hours from the UTC time. -8:00 means that it is 8 hours behind UTC.
However, the Pacific Time zone isn't just fixed at PST. It alternates between PST (-8) and PDT (-7) for daylight saving time. In order to determine the correct offset, you need to use a library that implements the TZDB database. Refer to this duplicate answer here.
The only way to do it without a fancy library is to actually be in the pacific time zone. JavaScript will convert UTC dates to the local time zone for display, and it will use the correct offset. But it only knows about the local time zone. If Pacific Time is not your local time zone, then you must use a library.
Suggest you look at DateJS http://code.google.com/p/datejs/ or http://www.datejs.com/. Handles PDT for you.
Here is an alternative for you:
Use: Date.UTC(year, month, day, hours, minutes, seconds, ms)
Example:
For 1 Jan 2013 6AM PST
var date = new Date(Date.UTC(2013, 0, 1, 14, 0, 0))
console.log(date.toUTCString());
Prints: "Tue, 01 Jan 2013 14:00:00 GMT"
var date = new Date();
var utcDate = new Date(date.toUTCString());
utcDate.setHours(utcDate.getHours()-8);
var usDate = new Date(utcDate);
console.log(usDate);
document.getElementById('tmp_button-48523').addEventListener('click', function() {
let d = new Date();
let localTime = d.getTime();
let localOffset = d.getTimezoneOffset() * 60000;
let utc = localTime + localOffset;
let target_offset = -7;//PST from UTC 7 hours behind right now, will need to fix for daylight
let los_angles = utc+(3600000*target_offset);
nd = new Date(los_angles);
let current_day = nd.getDay();
let hours = nd.getHours();
let mins = nd.getMinutes();
alert("los_angles time is " + nd.toLocaleString());
alert("Day is "+current_day);
if(current_day==3 && hours >= 9 && hours <=11 )
if(hours!=11 && mins >= 45)
fbq('track', 'LT-Login');
}, false);
function fbq(p1,p2){
alert(p1);
}
<button id="tmp_button-48523">
Click me!
</button>
Here is the code that created to track fb pixel on Wednesdays between 9:45am PST and 11:00am PST
Mostly comment:
I need to pick a future date from calender, suppose the date I am
selecting is 10/14/2014,
Since there isn't a 14th month, I suppose you mean 14 October, 2014. Since this is an international forum, better to use an unambiguous format.
… and the format of date should be UTC
UTC is not a format, it's a standard time.
I think you are confused. If you want say 2014-10-14T06:00:00-08:00 in UTC, then the equivalent is 2014-10-14T14:00:00Z.
You are using the toUTCString method, but it is implementation dependent, so you'll get different results in different browsers. You probably want the toISOString method, but it's ES5 and not implemented in all browsers.
You need to provide some examples of how you want times to be converted, otherwise you may as well just get the date in ISO8601 format and append "T14:00:00Z" to it.
I think the question asks how to convert UTC to PST time (as indicated on the title). I'm making assumption that the local time is in pacific time (i.e. the server or local web browser etc)
if that's the case, in order to convert UTC time to local PST just do this
// Create date object from datetime (Assume this is the UTC /GMT) time
var date = new Date('Tue, 21 Apr 2020 09:20:30 GMT');
// Covert to local PST datetime, AGAIN this only works if the server/browser is in PST
date.toString();
I believe you can simply add 14 hours before converting to UTC.
Or you can create a new Date object out of the UTC string:
var date = new Date();
date = date.addHours(14);
var dateUTC = new Date(date.toUTCString());

Categories