How do I determine if an entry in my database (laravel) was stored during Daylight Savings time using the created_at field?
I'm trying to calculate the time difference between when a record was saved and now so I can do can show something like 3 hours ago or 49 minutes ago. This was working fine, until the UK entered Daylight Savings Time a couple of weeks ago and now all times are inflated by 1 Hour.
I'm using moment to show the result like the following;
getElapsedString(from) {
return moment(from).fromNow();
}
The data is stored in my database in the following format and this is what is passed in to the above function as from;
2019-04-10 09:27:48
I'm not doing anything to the dates when they are stored. This is handled by Laravel.
Inside config/app.php there is a
'timezone' => ''
you can set it to:
'timezone' => 'America/New_York'
It will set the default timezone and save created_at with this timezone with current daylight
Related
I have a particular system configuration where my timezone is setted at (UTC-03:00) but I configured the system time to an hour after (e.g: Originally my time using the timezone must be 14:41, but I updated to 15:41).
What I want to know if there is a way using any library to know that the time is not correlated with the timezone.
Other solution could be to resolve the time using moment or other library returning the time using the system timezone and not the system time.
I tired using Date or moment with moment-timezone with no luck.
E.g:
System Time: 15:46 (+1 Hour configured manually)
Timezone Time: 14:46 (This should be the hour if isn't updated)
moment() //result Wed Nov 17 2021 15:46:19 GMT-0300
What I want is
moment().someFunc() //result Wed Nov 17 2021 14:46:19 GMT-0300
// Could be a function, property, just a difference to use it in order
//to compare with other date that comes from the server
If you try to get the utc date time (with moment().utc()) the result is your time less utcOffset and there isn't somthing about that in the documentation, so I think there isn't a way to do what do you want.
an alternative is to get the time from a external server like code bellow, but I hope for you that someone else know a way better
async function myTzTime() {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const { data: { datetime } = {} } = await axios.get(`http://worldtimeapi.org/api/timezone/${timezone}`);
console.log('--->', datetime)
}
myTzTime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.24.0/axios.min.js"></script>
I've been looking for a solution to this but as yet I've not found exactly what I'm looking for. I have the following issue:
A user selects a time in my react-native app. I store this in an SQLite DB as a datetime.
The user can edit said stored time and the DB is updated.
When the user selects a time from the input, a date is constructed from it and the time is outputted on-screen to show their selection after dismissing the input.
This all works OK if my user is in one timezone.
Unfortunately, if the user were to travel to another timezone the DB value is adjusted and the wrong time is displayed on the edit screen.
So, if I select the following on my form: 7:00am
My DB will store (for example) Sun Oct 01 2017 07:00:00 GMT+0100 (BST)
If however, I move my timezone to Tokyo and edit the time in my app, it is adjusted and shows a different value to 7:00am.
Here is the code I use to construct the date that is passed into the DB:
var date = new Date(Date.parse('2017-10-01T' + hours + ':' + mins + ':00Z'));
var _ofst = date.getTimezoneOffset() * 60000;
date = date.getTime() + _ofst;
(where date is stored)
Now, I know the offset is going to skew things but if I don't use it, my on-screen feedback to the user is adjusted to 8:00am due to my local current timezone.
What I want to do:
As an example, when a user selects 7:00am:
it should show this on screen correctly when a user picks a time (e.g. 7:00am)
it should store this in the DB correctly (Sun Oct 01 2017 07:00:00)
if the user moves timezone, I don't want it to adjust the stored value. (I want 7:00am to be the time used in-app)
I know I could use string manipulation to extract the stored time from the DB and re-construct the date on the way out but I am wondering if there is a less hacky approach which will maintain the chosen time regardless of where the user is in the world.
I want to use this time for notifications so if a user picks 7:00am they should see the notification at 7:00am.
Update
I think I've found a good way to manage this using moment.js which handily is part of node_modules in React-Native.
By using:
var date = moment('2017-10-01T' + hours + ':' + mins + ':00Z').utc().format();
I can ensure that the date stored in my DB is:
2017-10-01T07:00:00Z
This means it isn't 'polluted' by any offset data and when I bring it back out of the db I can use the same moment code to recreate my non-offset datetime.
Initial tests are proving successful using this method. All hail moment.js!
You are way overthinking things here.
If you don't want the time to adjust for timezone.. simply don't adjust.
A timezone anchors your time to a geographic location. You don't want that.
Store the selected time (e.g. 7:00 am) without a timezone, and just compare it to the local time.
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 trouble when converting from time zone to time zone using moment.js.
This is my code:
convertSelectedTimeZoneToClients() {
let timeZoneInfo = {
usersTimeZone: this.$rootScope.mtz.tz.guess(),
utcOffset: this.formData.timeZone.offset,
selectedDateTime: this.toJSONLocal(this.formData.sessionDate) + " " + this.formData.sessionTime
};
let utcTime = this.$rootScope.mtz.utc(timeZoneInfo.selectedDateTime).utcOffset(timeZoneInfo.utcOffset).format("YYYY-MM-DD HH:mm");
let con = this.$rootScope.mtz.tz(utcTime, timeZoneInfo.usersTimeZone).format();
return con;
}
The user picks date, time and time zone from drop downs on client page.
In timeZoneInfo object I am storing usersTimeZone (I want to be able to convert timezone that user selected on page and convert it to his local time zone).
For example user picks: 11/08/2016 01:30 and UTC+2 timezone and his timezone is UTC+1, than I want to show him in label: That is 11/08/2016 00:30 since UTC+1 is -1 hour comparing to UTC+2 timezone.
I store offsets for time zones in one object and those values are hard coded (utcOffset: this.formData.timeZone.offset).
Before I convert time form time zone to time zone I do this: get time zone -> convert to UTC time -> convert to user time zone.
What is happening is that utcTime variable has correct value. But when I pass that value and users time zone to .tz() function and using format() to get some readable value I get same time as utcTime like shown in picture:
I have read moment.js docs and by them this .tz().format() should do the work, but as you can see my result is: 2016-11-08T23:30:00+01:00.
So it gets that is should be incremented by 1 hour but how to accomplish to get: 2016-11-09T00:30 instead?
I have tried .format("YYYY-MM-DD HH:mm") as well same problem. When I use .local() function that should convert from utc time to specified time zone same problem is present.
Am I getting something wrongly? I am pretty sure that when you convert from 2016-11-08T23:30 UTC to UTC+1 it should be 2016-11-09T00:30, or one hour forward. Does someone sees something strange in this code?
I'm a fresher Magento developer. I wanted to display and use current/accurate day and time in my website.
Currently I am using system time in the website based on which html div are being displayed, which is not right for further since every system date and time are not configured correctly.
I have tried using Google Timezone api, but I have no idea on how to use it. Although it is displaying the country name but how to extract weekday and time from that timezone using JavaScript.
Alright, you want the week-day: very simple. You can first fetch the entire string from the endpoint http://www.timeapi.org/gmt/now?\a%20\I:\M:\S. This will give you the current time in the form of <weekday> <time>.
For example: Tue 07:17:02. Now, the Indian Standard Time (IST) is GMT +05:30. So, let's extract the details and do some basic math:
// ... I am assuming that you've fetched the date using some request and it's not in the variable.
var dateGot = "Tue 07:17:02";
var weekDay = dateGot.split( ' ' )[0]; // Yeah! You can now use the week day.
// Now, you need to add 5 hours and 30 minutes to the second part of 'dateGot'.
// ... time adding routine
var addTime = function ( originalDate, hours, minutes ) { ... }
var currentTime = addTime( dateGot.split( ' ' )[1], 5, 30 );
// Now you can use 'weekDay' for the current weekday and 'currentTime' for the current time.
This API provides a service to get the date-time. A simple example is to wrap it up in jQuery AJAX calls, and then use it.
Example:
http://www.timeapi.org/utc/now?format=%25a%20%25b%20%25d%20%25I:%25M:%25S%20%25Z%20%25Y
Gives
Tue Nov 10 06:49:28 +00:00 2015
You can hack it according to your liking.
As per your wish, we can have it display only the weekday:
http://www.timeapi.org/utc/now?\a
which gives
Tue