How to specify Local Date and Time in JavaScript - javascript

I have an Android App and I wanted to display notification at a given date and time (all local). However if I use UTC format like this which I fetch from server thru json:
2016-04-14T11:30:00Z
the message gets displayed at the same time across the globe using this functions:
var mTime = new Date( element.dateNtime );
What I want is to display the message at 11:30 AM of local time everywhere. Like 11:30 AM in UK all the users will get the notification, but the users in the US will get the notification 5 hours later, i.e. 11:30 local time (EST or whatever).
Update
I think I have found a solution, but from the answers below it appears that the question is either not too clear or is not understood. Here is the scenario:
a. My Cordova App is opened by the user on his mobile
b. The App reads a string date and message from the server at startup in this format "2016-04-14T11:30:00Z". So there is no question of getting current date using new Date() function.
c. Based on this the App sets up a notification for the given date and time using notification plugin of Cordova.
d. When the time comes the notification pops up
The solution is to use NON-ISO format for date, i.e. "'Wed, 09 Aug 1995 00:00:00'" along with Date.parse() function. Using the above example the code will become:
var mTime = Date.parse( element.dateNtime );
If the date is provide in this format ('Wed, 09 Aug 1995 00:00:00') variable mTime will contain exactly the same value. However if the datetime is provided in ISO format ( 2016-04-14T11:30:00Z ) then mTime will contain the time converted to the user's Locale.

If you are using PHP server you can easily achieve by using below code:
$serverdate = date("d m Y");
$indiantime = date('d/m/Y h:i:s A', time()+19800);
Here variable 'serverdate' returns the current date of server , and variable 'indian time' stores the time as Indian Standard Time
For converting time to proper zones use this formula
x * 60 * 60
Where 'x' is the GMT difference, In the case of India its 5.30
so 5.5 * 60 * 60 = 19800

Just instantiate a new Date object
var now = new Date();
That will create a new Date object with the client's local time. To display like 8:30 AM, use
var time = new Date().toString("hh:mm tt");
You can use new Date().getTimezoneOffset()/60 for the timezone. There is also a toLocaleString() method for displaying a date using the user's locale.

Related

Timezone independent dates javascript

Using javascript/react native + redux i need to save timestamps in a time format that is aware of local time when saving the date, but unaware when reading the same date in another timezone.
Take a hypothetical user that travels west around the world in one day, saving a time stamp every hour, all i different timezones, all at 2021-01-30 at 18:00 hours local time. Resulting in 24 timestamps at 18:00.
Using a function in the likes of isWithinInterval from date-fns in a similar fashion as below, all timestamps should return true.
isWithinInterval(
timestamp,
{start: new Date(2021,0,30,17,30}, end: new Date(2021,0,30,18,30)},
) // -> true
How do one go about doing this? Preferrably in a react-redux compatiable (serializable) way. By default, your date object will be saved in UTC based on the local time on your device.
I had such a hard time to wrap my head around the date objects that it took a long time for me to understand that this problem is actually what "date-fns-tz" package is all about. This is how i'm currently solving it:
Create a utc-time identical to the local time
using:
import {zonedTimeToUtc} from "date-fns-tz"
const myDate = new Date() // eg 2021-02-03 10:00 UTC +5
const localTimeIdenticalUtc = zonedTimeToUtc(localDateObject, localTimeZone) // 2021-02-03 10:00 UTC +-0
When i want to use the UTC-date, i transfer it back to an identical localDate for whatever time zone i am in.
import {utcToZonedTime } from "date-fns-tz"
const zonedTimeToUtc(localTimeIdenticalUtc, localTimeZone) // 2021-02-03 10:00 UTC +5

What do we mean when we say store time as UTC? [duplicate]

This question already has answers here:
When is it ok to store datetimes as local time rathen than UTC?
(1 answer)
How to store repeating dates keeping in mind Daylight Savings Time
(1 answer)
Managing timezone & DST issue for javascript application
(1 answer)
java Calendar, Date, and Time management for a multi-timezone application
(1 answer)
Closed 3 years ago.
I have a scheduling application, with a calendar that I build from scratch.
As a lawyer, you should be able to configure your available times for booking, like below:
A lawyer's availabilities in Australia
:
1- 10/01/2020, from 07:00am to 08:am
...
Here's what I do :
1- Get the epoch number of the entered date in Javascript :
const dateFrom = new Date(firstOfJanSevenAm).getTime() // 1578600000000
// Fri Jan 10 2020 07:00:00 GMT+1100 (Australian Eastern Daylight Time)
const dateTo = new Date(firstOfJanEightAm).getTime() // 1578603600000
// Fri Jan 10 2020 08:00:00 GMT+1100 (Australian Eastern Daylight Time)
2- Send this to NodeJS server and save it MongoDB
Mongoose.save({
from:dateFrom, //1578600000000
from:dateTo //1578603600000
})
3- Represent it inside the Calendar :
<div>{format(from, 'HH:mm')}</div>
Everything is working as expected.
Now, this lawyer is traveling to the US and he's in a coffee shop using the US local time ( any city), he opens the Calendar, he wants to add some availability, but in Sydney time. I need to provide him with a timezone dropdown so he can tell me that he wants the new date to be based on his home, Syndey.
Question :
1- Do I save the date as I'm doing ( as a number ), and save the timeZone separately next to it, and when representing it, just apply the timeZone?
Mongoose.save({
from:dateFrom, //1578600000000
from:dateFrom //1578603600000
currentTimeZone : 'America/Costa_Rica',
desiredTimeZone: 'Australia/Sydney'
})
<div>{formatWithTimeZone(from, 'HH:mm',desiredTimeZone)}</div>
Is this all I have to do? Or am I naively missing something that is going to trip me down the road?
And back to my original questions, where do I do the whole "always store time as UTC" thing?
All I've realized is, when I use the library that I'm using date-fns-tz and try to convert the user entered date to UTC, I get exactly the same output :
const dateFrom = new Date(firstOfJanSevenAm).getTime() // 1578600000000
const dateFromUTC = zonedTimeToUtc(dateFrom,currentTimeZone) // 1578600000000
// currentTimeZone is America/Costa_Rica, when he is in Costa Rica's caffee shop.
enter code here
1578600000000 === 1578600000000 = true
So why do I get the same output when converting the entered date, to it's UTC date?
I am going to give you an answer decoupled from the technical implementation.
Let's think by contradiction, you have a lawyer living in Australia and another living in Switzerland, what happens if you decide to store time in their preferred location?
You then need to save two information: the time of course (11 am) but it's relative so you also need to store the timezone (11 am in Australia) or (1 pm in Switzerland)
Now what happens if your lawyer travels to France? Do you want to update all his calendar information? 11 am is not 11 am anymore.
UTC solves this problem, you just need to store 11 am or 1 pm. UTC is arbitrary absolute, universal by convention.
So your backend/database should store this kind of information in UTC, always. And you need a way to know your user's timezone, maybe it's possible to update it using a web interface and it could be stored in a user database or just cookies. Maybe you want to derive it yourself by using your user's location, IP, browser's language, whatever.
Now that you know his timezone, your server can send UTC (absolute) time to the client and the client can seamlessly display the correct (relative) time.
The client deals with relative time, the server always makes it absolute.
So why do I get the same output when converting the entered date, to it's utc date?
The value returned by getTime is the number of milliseconds since 1 January 1970 00:00:00 according to universal time.
Therefore, UTC and getTime both represent a moment in time using the same universal timezone.
Do I save the date as I'm doing, and save the timeZone separately next to it, and when representing it, just apply the timeZone?
Don't save the timezone with the date. Just save the date in universal time. If you need to save timezone. That should go in user settings. However, you can guess the timezone; therefore, you don't need to save this information.
Saving the date
When you do save the date to the database, it should be represented by a UTC time string or by a UNIX timestamp, both options demonstrated below.
UNIX timestamp
UNIX timestamp should be in seconds. getTime returns milliseconds. You can just divide by 1000 to get the UNIX timestamp.
const unixTimestamp = new Date('December 17, 1995 03:24:00').getTime() / 1000;
UTC Date string
const utcDate = new Date('December 17, 1995 03:24:00').toUTCString();
Displaying the date
When you get the date from the back-end, then, converted it to the correct timezone.
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
const fromUnix = utcToZonedTime(1578423483, timezone)
const fromUtc = utcToZonedTime('Fri, 02 Feb 1996 03:04:05 GMT', timezone)
Closing thoughts
Dealing with timezones can be confusing. I am not to familiar with date-fns-tz. If you have the option, I would suggest migrating to Moment.js. Moment.js is the de facto standard JavaScript library these days - I highly recommend it.

Why new Date set as today gives back yesterday [duplicate]

This question already has an answer here:
Why is new Date() removing a day? - Javascript [duplicate]
(1 answer)
Closed 6 years ago.
This is the first time that I get this result.
I'm using a Telerik control RadDatePicker and I'm assigning the date client-side.
The thing is that the control doesn't accept a string as date, but a Date object in javascript
So, my code to set the date in the control is
var radDateControl = $find("radDateControl");
radDateControl.set_selectedDate(new Date('2016-04-26'));
But, I realized that the new Date is returning the date as yesterday! Why?
It's 5:58pm Eastern Time (US & Canada) right now. And if I do this
alert(new Date('2016-04-26'));
I get this
Mon Apr 25 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
Why and how can I get the day as of today.
Update
What I finally did it was this. Hope it can help others.
var dateAsString = "2016-04-26";
var year = dateAsString.split('-')[0];
var month = dateAsString.split('-')[1];
var day = dateAsString.split('-')[2];
var date = new Date(Date.UTC(year, month - 1, day, 0,0,0));
date.setTime(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
rpdDateControl.set_selectedDate(date);
The newly created date object is totally correct. The wrong part in here or at least the part confusing you is your browser, parsing the date object into your current timezone.
If you create a new date object and save it into a variable ...
var date = new Date('2016-04-26');
... you will get what you've asked for. A Date object representing the 26/04/2016 (in UTC).
Since you use your browser to get your date objects value, the value just gets parsed through your local timezone (in your case Eastern Daylight Time). So if you want to handle the correct date which you've used to create the new date object, you may use .toUTCString().
I know, parsing timezones can be really frustrating. In order to handle different timezones, you may try out Moment or Moment Timezone. I guess moment should fit your needs, but just for the completion.
Just use Date.now() instead. I'm not sure why the string isn't working but this will work anyways.
You are asking date 26, but with timezone changes it gives you back 2 hours, why not just alert(new Date()); and let it give you its current date?, also to check it go to the server using ssh and type date, if its not the date you are you can use tzselect to modify the server to your date

Convert specific date & time based on user location to utc date & time

I am working on a JavaScript based application. In my application, we have built a list from which user can select a time.
The list looks like this
Once the user selects a time from the list, based on todays date, I need to convert the date (which is today's date) and the time picked by user into UTC time.
There are tons of post which talks about converting date time into UTC but each having its pros & cons. Some of the post are old and JavaScript is evolving everyday.
I need to take users location into consideration while converting the date. I will assume what ever location/timezone set on user machine as the right location / timezone.
var userTime = new Date(); should give you something like:
Sun Dec 27 2015 21:58:08 GMT-0600 (CST) when you call userTime.
You can either do some simple math there, or you could use
userTime.toISOString(); and have the GMT time converted for you, e.g.
"2015-12-28T04:04:07.626Z"
If you need to find location you can HTML5 geolocation otherwise new Date wll return the Date object
You can do it either by using .toISOSTring() or by using .toUTCString().
(function(){
var a = new Date();
// Using .toISOSTring
document.getElementById('demo').textContent = a.toISOString();
var b =new Date(new Date().toUTCString().substr(0, 25))
document.getElementById('demo1').textContent = b
}())
WORKING MODEL
EDIT
You can also come up with a function to return a result in UTC format
function convertDateToUTC(date) { return new Date(date.getUTCFullYear(),
date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(),
date.getUTCSeconds());
}
WORKING MODEL 2

Server's time zone to be considered when opening application's UI from client machine

Our application is built using Java where we get Server time using datetime object. But when used from javascript I can't use the value as it is because value sent for UI is in string format (I don't know whether JSON attribute value retains date type in ajax when used from UI) and I want to use that value for pointstart of Highcharts and it expects the value to be of type Number.
So when I get value from REST, date will be in json format and type will be of type string. If it is converted to Date object, then it is converted back to Client's machine.
I have seen many suggestions and one among those is adding offset for the local time and I picked this for solving my problem(refer Convert date in one timezone to another timezone using timezone abbreviations for details on the solution). But in this at last it is converted to local string which is again not considered from HighCharts for pointstart. If I remove toLocaleString from Date object and try, the value what is receive is as below
"Tue Oct 20 2015 23:05:37 GMT+0530 (IST)" where Date value Tue Oct 20 2015 23:05:37 (server time) is of PDT time but time zone value appended is "GMT+0530 (IST)" (client time zone). Value is correct but can't consider as client time zone is appended. What's wrong in this?
please let me know
Code snippet:
// create Date object for current location
var date = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var newDate = new Date(utc + (3600000 * offset));
// return time as a string. But im removing this since i dont want of type string
return "The local time in " + city + " is " + newDate.toLocaleString();

Categories

Resources