I am working on a web application that needs stores a start and finish value for a work shift. The application has a timezone selection component which updates any date/time values in UI to match the time in a given timezone/location by changing a timezone cookie. Values are stored in a database as UTC values and they are passed through a controller to convert them between the DB and UI.
I am working on a page that has an exception where the start and finish times are changeable/editable by the user after saving. The page will get these values from UI Date Boxes. The values can convert to UTC on saving values with no issue with use of Luxon, however, a user can navigate back to the given page to edit saved values if changes are needed. When this happens, the saved values are loaded into these DevExpress/DevExtreme date boxes but they are not displayed as expected.
The values come from an odata response and is read as response.value[0].Start. When getting the value, an offset is applied based on the users cookie location, so in my case (Europe/London timezone) the response would be 2022-05-24T01:00:00+01:00.
I can convert this to UTC using DateTime.fromISO(response.value[0].Start).toUTC() to give me a value of 2022-05-24T00:00:00.000Z which is expected.
However I am running into converting this value to the desired value for a selected timezone. I try to do so with the following:
var DateTime = luxon.DateTime;
//selectedTimeZone found from cookie.
// -- logic --
if (response.value[0].Start != null) {
var dateBox = $("#ShiftBeginning").dxDateBox('instance');
var converted = DateTime.fromISO(response.value[0].Start).toUTC().setZone(selectedTimeZone, {keepLocalTime: true});
dateBox.option({ value: converted});
}
//Example selectedTimeZone: Asia/Tokyo
//converted.toString() value: 2022-05-24T00:00:00.000+09:00 (Tokyo time zone)
//Displayed UI Time value: 16:00
//Displayed UI Time value with {keepLocalTime: false}: 01:00
It appears as if the value of converted is having the offset applied twice, with an hour then taken off of the time to represent UTC.
I have tried changing parsing this value to different formats, tested different timezones, using standard JavaScript Date object etc. and I am beginning to run out of ideas.
Any help is appreciated to help solve this.
It's being "converted" twice because the time picker doesn't respect the zone in your cookie, because it doesn't know about it. Remember that the time is the time; the zone and how the time is represented in that zone are more like metadata. So it's expressing the time in user's system zone, and the local time it displays is off from what you expect by the difference between where they are and Tokyo's local time.
What you want to do is:
find the local time in Tokyo for your time. This is probably just DateTime.fromISO(s).setZone(selectedZone). You don't want keepLocalTime because your time is correct
change to the user's system zone, but keeping the time constant, which is just converted.setZone("system", { keepLocalTime: true }). We do this because we want a local time that is, technically, wrong; it's what local time matches the right Tokyo time. This is more-or-less the purpose of keepLocalTime: to trick zone-unaware components into showing a local time in another zone.
It's a little odd that you're passing the Luxon DateTime directly to the time picker. I guess it's calling valueOf() on the value you pass in. But you'd probably want to do that yourself to be confident you're telling it the right thing.
So all together:
var converted = DateTime
.fromISO(response.value[0].Start)
.setZone(selectedTimeZone);
.setZone("system", { keepLocalTime: true });
dateBox.option({ value: converted.valueOf() });
Related
This will be my first time working with time zones, I hear this is a major pain point for a lot of developers so I'm asking this question as a sanity check to make sure I'm not missing anything.
My use case is rather "simple", I want to have a date time picker where the user can choose their date and time in their local timezone (in other words what they see in the picker matches what their computer's date and time is set to).
Then I want to take this chosen date and time, convert it to UTC and send it to the server to be saved.
When the user goes to certain pages I take the UTC date/time coming back from the server and convert it to the user's local date/time and display it to them in a user friendly way.
Do I need a library like moment timezone for this or will the browser's native date methods like Intl.DateTimeFormat, new Date().getTimezoneOffset(), etc be enough? (I only need to support the latest modern browsers so I'm asking this from a "does it do what I need" ​point of view not a browser support POV).
It seems all I need are 2 things:
A way to get the user's timezone offset from UTC (so I can convert their local time to UTC to send to the server and also to convert UTC back to their local time to display it to them on certain pages)
A way get their timezone abbreviation (EST, PDT, CDT, etc) to show in the UI
Do I need a library for these? And if not why do people use such large libraries for working with timezones anyway?
You don't need a time zone library for the functionality you mentioned.
// Get a Date object from your date picker, or construct one
const d1 = new Date("2020-08-02T10:00");
// Convert it to a UTC-based ISO 8601 string for your back-end
const utcString = d1.toISOString();
// Later, you can create a new Date object from the UTC string
const d2 = new Date(utcString);
// And you can display it in local time
const s1 = d2.toString();
// Or you can be a bit more precise with output formatting if you like
const s2 = d2.toLocaleString(undefined, {timeZoneName: 'short'});
console.log("UTC: ", utcString);
console.log("Local Time (default string): ", s1);
console.log("Local Time (intl-based string): ", s2);
Keep in mind that not all time zones will have an abbreviation, so those ones will give output like "GMT+3".
I have a timestamp from the backend and I want to display it with momentjs per console.log() without timeshifting and completly indepented from my browsers timezone. I read many posts on stackoverflow but nothing works. All of my outputs have some timezone included.
let timestamp = "2019-11-19T07:05:00+01:00";
console.log(moment(timestamp).toISOString(true));
console.log(moment.utc(timestamp).format());
console.log(moment.utc(timestamp).toISOString(true));
console.log(moment.parseZone(timestamp).format());
console.log(moment.parseZone(timestamp).local().format());
console.log(moment.parseZone(timestamp).utc().format());
console.log(moment(timestamp).utcOffset(timestamp).toISOString(true));
console.log(moment.tz(timestamp, 'Europe/Berlin').toISOString(true));
console.log(moment.tz(timestamp, 'Europe/Berlin').format());
console.log(moment.tz(timestamp, 'Europe/Berlin').unix());
console.log(moment.parseZone(timestamp).format('MM/DD/YYYY HH:mm:ss'));
console.log(moment(timestamp).utcOffset("+0100").format('YYYY-MM-DD hh:mm:ss'));
expected output:
2019-11-19T07:05:00Z
The Timezone of the timestamp is: Europe/Berlin
My Browsers timezone is switched to something different.
I don't understand why this simple problem has no easy solution. :)
To meet the requirement you described (keeping the local time while changing the offset) you can do the following:
var result = moment.parseZone("2019-11-19T07:05:00+01:00").utcOffset(0, true).format();
console.log(result); //=> "2019-11-19T07:05:00Z"
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Step by step explained:
moment.parseZone("2019-11-19T07:05:00+01:00") // Parses the string, retaining the offset provided
.utcOffset(0, true) // sets the offset to zero while keeping the local time
.format() // formats the output, using Z to represent UTC
However - You should recognize that these are not the same moments in time. The output timestamp is one hour earlier than the input timestamp. This is explained in the documentation as follows (emphasis mine):
The utcOffset function has an optional second parameter which
accepts a boolean value indicating whether to keep the existing time
of day.
Passing false (the default) will keep the same instant in Universal Time, but the local time will change.
Passing true will keep the same local time, but at the expense of choosing a different point in Universal Time.
Thus, it is usually the wrong choice when you already have a specific point in time, either in UTC or as an offset from UTC (like your example input value).
Instead, you should expect that converting from local time to UTC will indeed change the date and time portion of the timestamp. You can use .utcOffset(0, false), or .utcOffset(0), or simply .utc() to do the conversion correctly.
I have one object called appointment which has two properties: StartDate and EndDate.
When I make POST request I send these values using ISOString time .
this.appointment.StartDate.toISOString()
On the server-side, I received these properties with correct values. Also, it seems to be correct when I create model in order to save appointment to the database. I used .ToUniversalTime() method.
var newAppointment = new Appointment()
{
StartDate =Convert.ToDateTime(model.StartDate).ToUniversalTime(),
EndDate = Convert.ToDateTime(model.EndDate).ToUniversalTime(),
SpecialityId = speciality.Id,
LocationId = location.Id,
PatientId = patient.Id,
UserId = user.Id,
Observations = model.Observations
};
But in database I found another values. Can explain somebody why is this behaviour ?
For instance, I used 2017.09.01 11:00 for StartDate and in database i found 2017-09-01 08:00
The server and database is located in the westeurope.
A few things:
Don't call ToUniversalTime in a web application. It's designed to convert from the server's local time zone to UTC. The server's time zone should be irrelavent to your application. Web applications should never use ToUniversalTime, ToLocalTime, DateTime.Now, TimeZoneInfo.Local, DateTimeKind.Local or any other method that uses the time zone of the computer it's running on.
Ideally, on the server side, your model.StartDate and model.EndDate would already be DateTime objects, because they'd have been deserialized that way. Therefore, you probably don't need to call Convert.ToDateTime. If they are strings, then I would adjust your model class accordingly.
On the client side, assuming StartDate and EndDate are JavaScript Date objects, and they were created using local time values (that is, the time zone of the browser), when you call toISOString, you're not just getting a string in ISO 8601 format - it is also converting it from the browser's time zone to UTC.
In your example, the UTC time is 3 hours ahead of UTC for the date and time shown. From your profile, I see you are located in Romania, which is indeed UTC+3 for this date, because it is currently observing Eastern European Summer Time. When Summer Time ends (on October 29, 2017 at 04:00), it will return to UTC+2. For this reason, you cannot simply add three hours to all values.
If you want to send local time values from the client, you should send them in ISO 8601 format, without any Z or offset, for example 2017-09-01T11:00. There are several ways to achieve this:
The best way is to not have them in a Date object to begin with. For example, if your input uses the <input type="datetime-local" /> input type (as specified in HTML5), the .value property is not a Date object, but rather a string in ISO 8601 format.
If you can't avoid a Date object, then create a local ISO string, like this:
function dateToLocalISOString(date) {
var offset = date.getTimezoneOffset();
var shifted = new Date(date - offset * 60 * 1000);
return shifted.toISOString().slice(0, -1);
}
OR, using Moment.js:
moment(yourDateObject).format("YYYY-MM-DD[T]HH:mm:ss.SSS")
Lastly, you will probably read advice from others about storing these as UTC. Don't listen. The advice "always use UTC" is shortsighted. Many scenarios require local time. Scheduling appointments is a primary use case for local time. However, if you need to act on that appointment, you'll use the current UTC time, and you'll also need some information about the time zone for the appointment so you can convert from UTC to the appointment's time zone. For example, if this is something like an in-person doctor's office appointment, then it's safe to assume the time zone of the doctor's office. But if it's an appointment for an online meeting, then you'll have to capture the user's time zone separately and apply it on the back end where appropriate.
The problem is with your current timezone.
What your application does is get current timezone (+3) in this case.
Now it got your timezone but it will convert to utc time. So what will happen, your current time will be -3 hours.
If you not adjust to summer and winter time then you can simply add 3 hours to the datetime. Otherwise you have to get the offset of your timezone and add that to the current datetime value.
Take care if you use this application in different timezones. For example You life in +3 and some else life in +2 timezone.
I put a UTC .NET/JSON date from .net on client side. When I run the following command:
moment(value.Planet.when).utc()
The returned date from webservice:
"/Date(1469271646000)/"
I get a date in the _d parameter showing the current accurate UTC date with GMT+0300 on right side.
I want to convert this time to local time on the user machine and what ever I do, I always get the time 3 hours back.
I do this:
moment(value.Planet.when).local().format('YYYY-MM-DD HH:mm:ss')
and I get the same date time as the UTC. I don't understand how can I get momentjs to show the UTC time relative to the local time. I checked that the momentjs object is indeed UTC.
I thought that if I pass the moment.utc() function the UTC date that I've got from the webservice (originally from the database), I can just run the local() function and I'll get the accurate hour relative to my area, but it didn't work.
You can use moment(date).format('YYYY-MM-DDTHH:mm:ss');
Eg:- if you date "/Date(1469271646000)/"
ip-> moment(1469271646000).format('YYYY-MM-DDTHH:mm:ss');
op-> "2016-07-23T16:30:46"
Do not use the _d property. It is for internal use only. See this answer, the user guide, or Maggie's blog post on the subject.
As far as you question of how to convert to local time, you don't actually need to convert at all. You're already parsing the input value in local mode, so you can just use it directly:
var m = moment("/Date(1469271646000)/"); // gives you a moment object in local mode.
var s = m.format(); // lets you format it as a string. Pass parameters if you like.
var d = m.toDate(); // gives you a Date object if you really need one
Try to avoid using Date objects unless they're required by some other controls or libraries you're using. Most operations can be done strictly on moment objects.
I am having an issue with displaying the correct time. I have a php script that when a button is clicked it inserts the CURRENT_TIMESTAMP into the database. The server is located in Arizona, I am in PST. When I call the time in my script it shows Arizona time, but I need it to show the users time. So 2015-02-18 16:06:28 Arizona time, MY time is 2015-02-18 15:06:28.
How do i get the correct time. I am using moment.js, but no matter how i format it it shows the incorrect time. I am not sure but is DST, not being considered?
var time_in = time_in;//format 2015-02-18 16:17:33
var timeIn = moment.utc(time_in, "HH:mm a").format("HH:mm a");
Moment.js parses the date as a locale date-time. So when you do moment.utc(time_in), you're converting it to UTC according to your local time (PST), shifted forward or backwards.
So what you need to do is do a moment.fn.utcOffset. Arizona is UTC-07:00, so we would want to add +7 to the offset. You can do the same using moment.fn.zone but that's getting deprecated.
var utcTime = moment.utc('2015-02-18 16:06:28').utcOffset(+7).format('YYYY-MM-DD HH:mm:ss')
// returns "2015-02-18 23:06:28" which is the UTC time
Now you have the moment in UTC, you can convert it to the client localtime:
moment(moment.utc(utcTime).toDate()).format('YYYY-MM-DD HH:mm:ss')
// returns '2015-02-18 15:06:28' (which is PST)
moment.utc(utcTime).toDate() above just converts the utc time to your local time, then formatting it with momentjs
EDIT: If possible, you should use unix timestamp when sending to server, then you don't have to deal with UTC or timezones. You can convert to local time with moment.unix(unixTimestamp).format('YYYY-MM-DD HH:mm:ss')
It looks like you are using Javascript to get the time of the client, but then not passing that to the PHP. I'm not sure how your app is structured, but you could create an input tag with the type="hidden". Then using Javascript, find the element and set it's value to Date().
Here is an example: http://jsfiddle.net/43jfefuq/
Now when you submit this form with PHP, the value in the field will be the client's local time.