I used a standard html datetime-local input like <input type="datetime-local" />, I put in a time of February 16th, 6 pm from my pc in the EST GMT-5 timezone. From another pc in the same timezone I display the date stored in DB from the input, but it shows February 16th, 1 pm instead of 6 pm. I know this is a timezone problem because there is a 5 hour difference and im in GMT-5. How would I convert the users input to UTC time based on their local time, then store it the db as a UTC time?
EDIT: I did new Date(...).toUTCString() on my server instead of on my client, does this have anything to do with the timezone problem?
(1) the data we get from datetime-local input is like this
const startTime = "2021-08-28T09:00"
There is no timezone.
The MDN link here:
datetime-local
(2):
When we send the data to the server (the server timezone may different in different environment) and save in the DB(normally always in UTC timezone) we need to make sure we send the right date time. Convert it to UTC time before sending to server.
We can do:
let result = new Date(startTime);
result.toISOString();
It converts to UTC. Then it will save in the DB as UTC.
Link here: toISOString()
(3):
We get the UTC data from DB, when it display on the FrontEnd, we need to convert to our local timezone and right format as below.
this.startTime = moment(this.startTime).format("YYYY-MM-DDTHH:mm");
Info here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local
<input type="hidden" id="timezone" name="timezone" value="-05:00">
Related
This question already has an answer here:
Why moment.js treats dash differently from slash?
(1 answer)
Closed last month.
I am trying to save a date and time for different time zones. I have changed my time zone in my chrome dev tools for testing purposes as follows
So for testing, I am trying to save a date time for London as '2023/04/21 23:55' when I save this datetimeoffset into my DB it gets stored as '2023-01-30T23:55:00+02:00'
but now when I try to read the format the date is as follows
var test = Moment(date); //'2023-01-30T23:55:00+02:00'
test = test.utc(true);
var format = "yyyy/MM/DD HH:mm";
return test.format(format);
it returns the date 2023/01/30 21:55. Why is it removing the 2 hours?
The issue is that your datetimeoffset has a timezone associated with it (+02:00). The 2023-01-30T23:55 part of your timestamp is not UTC time, it is local time, and the +02:00 signifies the offset of that timezone.
I'm not sure how you're saving that time in the first place, you probably forgot to specify the timezone as UTC. For example, if the date was created with Moment('2023-01-30T23:55:00'), then it that time will be intepreted as 23:55:00 on 2023-01-30 in the system's timezone, not UTC. To fix this, you need to use the Moment.utc('2023-01-30T23:55:00').
My customer's store is in GMT +5:30 timezone but the user's locale is in GMT +8 timezone.
Currently, I'm using javascript's .toISOString() function to convert to UTC and storing UTC in the database. I retrieve UTC from the database and send exactly that the browser, so the new Date('2019-11-15T00:00:00Z') function converts the UTC to the browser's locale.
But, if the user opens a record created by GMT +8 timezone user or vice-versa, the dates are getting messed up.
I'm thinking it would be good if I can transfer the exact date the user enters in the browser and send that exact date to the backend to easily offset using the store's timezone?
The frontend is in VueJs and the backend is in C#.
Always store UTC time in database
Just Store the UTC time in your database, In your client-side, Get client's current timezone,
Here, I am getting IANA timezone from client's system
// get client's timezone (From user's system)
var clientTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
Then, Convert the UTC depends on the timezone and show it to user,
// assume 2019-11-15T00:00:00Z is the UTC date from your database
var convertedTime = new Date('2019-11-15T00:00:00Z').toLocaleString("en-US", {timeZone: clientTimezone});
Example
var clientTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
var timeUtc = '2019-11-15T00:00:00Z';
var convertedTime = new Date(timeUtc).toLocaleString("en-US", {timeZone: clientTimezone});
console.log("Time to Current User : " + convertedTime);
var timeInUsa = new Date(timeUtc).toLocaleString("en-US", {timeZone: "America/New_York"});
console.log("Time in America (New York) : " + timeInUsa);
var timeInAustralia = new Date(timeUtc).toLocaleString("en-US", {timeZone: "Australia/Brisbane"});
console.log("Time in Australia (Brisbane) : " + timeInAustralia);
Note that the js Date object is simply a number that represents an absolute time (independent of any timezone).
So the best encoding/format for transferring and storing a date is that number. IMO this is much simpler than storing a UTC string.
So, on the end-user's machine you would Date.parse the date string provided by the user and this would take account of the user's time zone for you and give you the absolute time number for sending and storing on your backend.
Don't do any formatting or parsing of dates on the backend if you are using Node because there are serious gotcha's and because you shouldn't need to anyway: any client device that needs a date string will do the formatting locally which will automatically convert it to the correct format for their locale and timezone. [edit: the Q did not specify the backend when I wrote this.]
You will need to watch for some gotcha's in the Date.parse function but these are minor compared to the node problems. The most significant IMO is that it will interpret dates in YYYY-MM-DD as ISO 8601 dates (which makes some sense) but then assume that they are GMT if no timezone is specified so you should make sure there is a timezone specified if you use that format.
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 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.
I have a date that is stored in my sql server database as 2013-06-12 00:00:00.0000000. But when I retrieve it with $.getJSON and then format it, the date is displayed as jun 11 2013. As a check, I displayed the value with out any formatting to make sure the correct value would render, in which it did. Can anybody give me a clue as to why a day is being subtracted from the original date when formatted. Here is the jquery code that i am using:
$.datepicker.formatDate('M dd yy', new Date(val.DeliveryDate))
Your dates are stored as GMT in MySql. When you grab them through your getJSON call, the date is converted to your local time zone. It's already tomorrow in England relative to us (8pm).