I am calling an Api that has the dates in the following format: 2020-09-08T00:00:00Z. I want to get the current date of the user and compare it against the API date to see how much time is left. The problem is that users could be in UK or IE and the second problem how can I be sure that there is not a daylight saving time issue here. I would also like to display the dates to the user.
const userDate = new Date() //current date
const apiDate = new Date('2020-09-08T00:00:00Z') //api date
if (userDate.getTime() <= apiDate.getTime())
//do something
Related
I'm working on a web application that supports link sharing. This link contains the clients selected dates (start and end date) from a date selector react component. As the user changes the selected dates they are accurately represented in the URL ready to be shared with other uses. When another user clicks on this link it should open the same web application except the default selected dates inside the date selector component will be parsed from the URL instead (if they exist otherwise uses the default).
This works exceptionally well when the links are shared between two people in the same time zone. However, if I send my link to someone in a different time-zone the selected dates for them are not the same as mine.
Currently when writing the local dates to the URL I am doing the following steps:
url.set("startDate", dates[0].toISOString());
url.set("endDate", dates[1].toISOString());
where date[0] and date[1] are date objects in the current users local time-zone.
When I parse the URL I do the following:
var startDate = new Date(url.get("startDate") ?? "");
var endDate = new Date(url.get("endDate") ?? "");
if (startDate.toString() === "Invalid Date") {
startDate = defaultStartDate; // user local time ( uses new Date() )
}
if (endDate.toString() === "Invalid Date") {
endDate = defaultEndDate; // user local time ( uses new Date() )
}
For example, I have two brokers running one in Eastern Standard and another in Pacific Standard. If I select 06/01/2021 and 06/05/2021 in Eastern Standard the link that is constructed looks like the following:
startDate=2021-06-01T04%3A00%3A00.000Z&endDate=2021-06-06T03%3A59%3A59.999Z
and when parsed by the user in Pacific Standard the resulting selected dates are:
05/31/2021 and 06/05/2021.
After some further debugging I believe this issue is occurring because the time set by default is 00:00:00 for start date and 23:59:59 for the end date. So when converting from EST -> PST new Date() is subtracting 4 hours from both dates (as it should). However, I need these to be the same dates across multiple time zones.
Given the strings are generated by toISOString, the resulting timestamp will be parsed to exactly the same time value by the built-in parser regardless of the user's system offset or settings.
The difference you see is from generating a local date and time from the time value based on different system settings. Given the same input timestamp, both systems should display exactly the same output timestamp if displayed for the same location, e.g. the following parses the timestamp in the OP, then presents the equivalent time in EDT and PDT respectively.
let s = '2021-06-01T04:00:00.000Z';
let startDate = new Date(s);
console.log(startDate.toLocaleString('en', {
timeZone: 'America/New_York',
timeZoneName: 'short'
}));
console.log(startDate.toLocaleString('en', {
timeZone: 'America/Los_Angeles',
timeZoneName: 'short'
}));
If you want the receiver to see the same date and time as the sender, then include the sender's IANA representative location (such as 'America/New_York' or encoded as 'America%2FNew_York') in the URL. But that doesn't change the generated time value, only the timestamp displayed by the various toString* methods.
I'm using devExtreme dxScheduler and i'm trying to display meetings after fetching them from api, the problem is that i can't recreate the original date format ("YYYY-MM-DDThh:mm:ssZ") since i'm getting the dates as timestamp.
Here is how it's stores :
var startDate = moment("2021-05-24T16:30:00.000Z").valueOf()
// 1621873800000
Here is what i'm trying to do to recreate the format:
var startDate = moment(new Date(startDate)).format("YYYY-MM-DDThh:mm:ssZ")
//"2021-05-24T07:30:00+03:00"
Notice that the original date ("2021-05-24T16:30:00.000Z") and the formatted date ("2021-05-24T07:30:00+03:00") are different ...hence the calendar do not displays them.
Looks like the date is being converted into your local timezone, thus the difference. You may need to add Moment Timezone to be able to get the timezone back in to recreate it to the format you need. Also consider adding utc() before the format to bring it to Zulu time.
Fix 1
I see from the DevExtreme page that it needs to be displayed within this format:
currentDate: new Date(2021, 4, 27)
Maybe you need to format it before adding it like this:
var check = moment("2021-05-24T16:30:00.000Z", 'YYYY/MM/DD');
var month = check.format('M');
var day = check.format('D');
var year = check.format('YYYY');
console.log(month,day,year);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
And then in your dxScheduler add the property like this:
currentDate: new Date(year, month, day);
Fix 2
If that's not the problem, you can install moment-timezone
var a = moment.utc("2013-11-18 11:55").tz("Asia/Taipei");
var b = moment.utc("2013-11-18 11:55").tz("America/Toronto");
a.format(); // 2013-11-18T19:55:00+08:00
b.format(); // 2013-11-18T06:55:00-05:00
a.utc().format(); // 2013-11-18T11:55Z
b.utc().format(); // 2013-11-18T11:55Z
In this example, you first create moment.utc("2013-11-18 11:55") object in UTC, and then change its timezone to specified. This also works if you create the object in your default timezone: moment("2013-11-18 11:55").
Note that created moments have equal UTC time because these moments were created in a default timezone.
Turns out that displaying a calendar event with DevExtreme requires only to use regular date object.... so no need to do anything spacial.
I have a problem in my application. I display date in this format DD/MM/YYYY example 09/07/2020. But the problem is in my form if the user lives in reunion island enters the date 10/07/2020 (the date of today plus one day), the user lives in France sees 09/07/2020.
How can do in javascript to have the same date enters by the user who lives anywhere.
I want to have this : User lives in Reunion island enters 10/07/2020 and the user lives in France sees 10/07/2020
This is a recurrent issue in JS, and the solution is not easy as Date is stored as local time in JS.
You can use an ISO string to input your time: YYYY-MM-DDTHH:mm:ss.sssZ.
Executing this:
new Date('2020-01-01T00:00:00.000Z')
Will give the same results.
If you can, i'll advice you to use Moment.js, it will you save a lot of effort if you plan to do date operations.
If you want to save absolute dates i would recommend you to use a library like moment-timezone and save the dates in utc.
In order to do this you should do two things:
Set the date in utc before sending it to the server:
const parseDateBeforeSend = (selectedDate) => {
const parsedDate = moment(selectedDate).tz('utc', true).startOf('day').toDate()
return parsedDate
}
Transform the date to utc before showing it to the user:
const showDate = (date) => {
const parsedDate = moment(date).tz('utc').format("DD/MM/YYYY")
return parsedDate
}
For your information:
When using tz function in step 1 you can see that it has a second parameter set to true, what this does is to keep the original time and only update the timezone. This would keep the original date you want to show.
In the second step we omit this parameter since we want to show the actual date saved in utc.
I admit I'm having a hard time understanding javascript dates and timezone conversions. Server side, in my node app, I'm trying to convert price/date data that only ever deals in MST timezone to javascript date objects, and save them to the database. Under no circumstances, server-side or client-side, do I ever want to convert the dates into any other timezone. I have this working except for one date in particular says Invalid Date when it is fetched from my mongodb database...
This is the original data that I need to reformat. It states the day and the hour the price was set...
02/17/2014 24
Effectively, this is 12:00AM on 02/18/2014, so I need to create that date object and save it into mongodb. Now, these prices are set on an exchange in a fixed timezone and I don't want any timezone conversions for any reason, but I kept getting them when I created my date object, so this is what I finally settled on. A combo of Javascript Date Objects and Moment.js help...
if (hour === "24") {
date = new Date(day+" 00:00:00");
date.setDate(date.getDate() + 1);
date = moment.tz(date, 'America/Phoenix').format("YYYY-MM-DDTHH:mm:ss");
} else {
date = new Date(full_date + ":00:00");
date = moment.tz(date, 'America/Phoenix').format("YYYY-MM-DDTHH:mm:ss");
};
And then I save that date into mongodb in a Date type property of my model...
This works for hours 1 - 23, but when I fetch data from my database from hour 24, it always returns Invalid Date
The day, month, hours, minutes, and seconds components in JavaScript dates are 0-based, so the range of values for "day" should be 0-23.
Since you are using moment.tz, it would be more straightforward to construct your dates by passing an ISO date string and doing the date math using moment.
Here are a few different ways to represent midnight on Feb 18th, 2014 with moment.tz:
> moment("2014-02-17").tz("America/Phoenix").add('days', 1).format()
'2014-02-17T06:00:00-07:00'
> moment("2014-02-18").tz("America/Phoenix").format()
'2014-02-17T06:00:00-07:00'
> moment("2014-02-18 0:00").tz("America/Phoenix").format()
'2014-02-17T06:00:00-07:00'
I have been reading up on dates for days, seemingly going in circles here. I have a string in a DB that looks like this
2012,03,13,01,31,38
I want to create a js date object from it so...
new Date(2012,03,13,01,31,38);
Easy enough, right? But it comes back as
2012-04-13 05:31:38 +0000
So the month is off by 1 and the time is off by 4 hours (maybe DST or Timezone related???). I simply want a date that matches the one I provided. Its driving me nuts, dealing with these JS date objects.
How can I be sure the date object is the exact same date and time as the string suggests, I have no need for Timezone or DST changes, simply a date that matches a string.
More specifics regarding application:
My application for this need is for an iphone app I am developing in Titanium (which builds using JS). Basically, part of my app involves logging data and with that log I collect the device's current date and time. I save all of this information to a mySQL database. The field in the database looks like this format: "2012-02-16 00:12:32"
Here is where I start to run into problems. I am now offering the ability to edit the log, including the date and time it was logged. In order to use an iPhone "picker", I must convert the string above into a JS date object again. This usually screws things up for me. I essentially need to create a new date object with the date above, with timezone and dst being completely irrelevant, so that when I save back to the DB, its just the string above, modified as per the users request. It needs to not matter whether they are editing in pennsylvania or china, they are editing the same log date.
Sorry if this has been confusing. I am having a hard time figuring out this whole date stuff.
This depends on what your string is. If that string is UTC time, you need to parse it as that. If it's local time, you need to parse it as local time. You can make a helper method like this for that part:
function getDate(utc, year, month, day, hour, minute, second) {
if(utc) {
var utc = Date.UTC(year, month - 1, day, hour, minute, second);
return new Date(utc);
} else {
return new Date(year, month - 1, day, hour, minute, second);
}
}
Now, to parse your string, you can use this:
function fromString(utc, str) {
var parts = str.split(',');
var year = parts[0];
var month = parts[1];
var day = parts[2];
var hour = parts[3];
var minute = parts[4];
var second = parts[5];
return getDate(utc, year, month, day, hour, minute, second);
}
which you can use like this for your example:
var d = fromString(true, '2012,02,13,00,31,38'); // If UTC
var d = fromString(false, '2012,02,13,00,31,38'); // If local time
Here's a working jsFiddle that you can play with:
http://jsfiddle.net/rNqXW/
which also shows two ways to print the date (UTC or local). Hope this helps.
I had the same problem. There are two reasons for the weird time change:
Use new Date(Date.UTC(2012,03,13,01,31,38)) to avoid the time change.
Note that the month is zero based! Months go from 0 to 11 for this function.