Converting between timezones without affecting the actual time? - javascript

I am trying to store and retreive a date object that is supposed to remain consistant on saving regardless of whatever timezone the browser is set to.
For example. I have a 7PM IST which when converted with an offset should return to 7 PM of a timezone that I select.
I then want to be able to retreive the same timestamp as 7 PM of whatever timezone the browser is in.
I have figured out the first part
var date = moment(date);
var localDate = date.clone();
localDate.tz(timezone); // continent/city from momentjs
localDate.tz(timezone);
localDate.add(date.utcOffset() - localDate.utcOffset(), 'minutes');
localDate.toDate();
which ultimately gives me the date and I can use to save into the database as UTC ( I am saving it in mongodb)
I am not sure on how I can reverse it back to the local timezone so that I can get the return value as 7PM of the browsers timezone.

convert the date into UTC format before you save to db
moment.utc()
Whenever you retrive convert from UTC to local time.
moment.utc(utcDateTime, utcDateTimeFormat).local().format(specifiedFormat)

Related

How to format a string in UTC to the configured timezone on Moment

I have the following string, which is in UTC:
2022-02-01T00:00:00Z
I have already configured my timezone, so I do not want to mess/call .tz()
I know that this string is in UTC, but I am not managing to convert from UTC to the defined timezone, which in this example is pacific/wallis.
I have tried many things, as
const utc = moment.utc('2022-02-01T00:00:00Z').toDate()
const inConfiguredTimeZone = utc.format()
My desire is to get this timestamp 2022-02-01T00:00:00Z and have converted to the defined timezone on Moment
I need to tell moment that "This string is in UTC, please give me the converted timestamp in the defined time zone"
If you just want to format a UTC timestamp in your current timezone (determined by your computer's time settings) just use
let s = moment("2022-02-01T00:00:00Z").format();
This will produce a string like 2022-02-01T12:00:00+12:00 if you are currently in a timezone that has a UTC offset of +12 hours (like pacific/wallis) or 2022-02-01T01:00:00+01:00 if you are currently in a timezone that has a UTC offset of +1 hours (like europe/berlin)
If you want it converted to a specific timezone use
let s = moment("2022-02-01T00:00:00Z").tz("pacific/wallis").format();
This will produce 2022-02-01T12:00:00+12:00, regardless of your current timezone.

Convert back the time that was converted from js getTime() in PHP

I have frontend that accept date from calendar, with this format: 9/02/2021 11:00 AM
it then converted into these format: 2021-02-09 11:00, then it converted by this line of code:
var timeStamp = new Date('2021-02-09 11:00').getTime() / 1000;
I know these produce time in this value: 1612843200
Now in backend, i want to read that time value, and want to convert it back into Y-m-d H:i format, i tried date('Y-m-d H:i', '1612843200') but the result is 2021-02-09 04:00
my purpose is to get the time back to date format, and set timezone to UTC later, but i stumble in the first part before set timezone to UTC
how can i get the date back again?
You can use Intl.DateTimeFormat to get the timezone of the user.
See the below code to get user timezone.
let userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(userTimeZone);
Then you can send the user timezone, along with the seconds that you are using to your backend server.
There you can set the date_default_timezone_set using the timezone you are getting from the frontend.
See a list of timezone here.
Based on your need you can change the date-time accordingly at the backend.
In your PHP, you can try something like this
$userTimezone = $_POST["userTimeZone"];
$userSeconds = $_POST["seconds"];
date_default_timezone_set('UTC');
//Set this to get UTC timezone
You can use the following code,
date('j/m/d H:i A', '1612843200')

Get Epoch time value for different TimeZone

My local time zone is IST , i tried to define timezone inside Date object like
const usaRegionTime = new Date(inputDate.toString()).toLocaleString(
'en-US',
{
timeZone: 'America/New_York',
}
);
const estDate = new Date(usaRegionTime);
console.log(estDate.getTime());// Uses IST(local time Zone) instead of EST(Specifed time zone)
Example:
My IST time is 7:15 PM and i use the Date object with EST timeZone i get correct EST as 9:45 AM but when i try est.getTime() UTC is calculated as 7:15 pm instead of 1:45 pm . Its taking 9:45 am as IST(Local time Zone) before converting to UTC(Epoch).
Problem is its Taking Browser local timeZone(IST) instead of TimeZone(EST) i gave as param to Date object to get Epoch value . Is there a way to override the Local time Zone with Specified TimeZone while getting Epoch value.
Is there a way to override the Local time Zone with Specified TimeZone while getting Epoch value.
No. You can generate a timestamp for any supported IANA representative location, but you can't "set a timezone" for the Date instance itself.
ECMAScript Date objects are just a time value that is an offset in milliseconds from 1 Jan 1970 UTC. They have no timezone and can only work in either the local timezone or UTC, that's it. When parsing a timestamp for a particular timezone, the result is a UTC time value. That is the only thing the Date instance remembers so it doesn't matter how you generate a Date, the time value is always effectively UTC.
The plain get and set methods like getYear, getMintues, etc. and the toString methods use the UTC time value and host settings to generate local date and time values. The UTC get and set methods like getUTCYear, getUTCMintues, etc. and toISOString, toUTCString etc. return UTC values. So you can work in either local or UTC, working in some other timezone or location requires you to do the work (which is quite complex and likely a library is a better option).
You can get a timestamp for any supported IANA representative location using toLocaleString with the timeZone option, however that only affects the generated string, it doesn't change the underlying UTC time value.
You can't set a timezone or location for a Date object as it doesn't have any property on which to set it, it's just a (UTC) time value, that's it.
Also, the built–in parser is not required to parse the output from toLocaleString, primarily because the user can configure the output to a huge number of different formats that may not include any date or time values (e.g. you can get just the timezone or offset). So depending on parsing such values is fundamentally flawed.
var date= new Date().valueOf(); //gives UTC timestamp in millisecond
const usaRegionTime = new Date(date).toLocaleString(
'en-US',
{
timeZone: 'America/New_York',
}
);
const estDate = new Date(usaRegionTime).toString();
console.log(estDate);

Convert hour to date time without adding +1

Hi im using moment js to convert this string 20:00 I tried:
var a = moment("20:00", "HH:mm")
console.log(a.format()) // 2016-09-08T20:00:00+01:00
the problem when I store in mongodb it become
2016-09-10T19:00:00.000Z
I want to store 2016-09-10T20:00:00.000Z
anyway can explain why please ?
When you say that you want to store 2016-09-10T20:00:00.000Z what you are saying is that you want to assume that your date and time is UTC.
To assume that the date you are parsing is a UTC value, use moment.utc
var a = moment.utc("20:00", "HH:mm")
console.log(a.format()) // 2016-09-08T20:00:00Z
Note that when you parse a time without a date, moment assumes the current date. This may not be the behavior that you want.
I'm also not sure if you want a UTC date (which is what you are saying), or a local date without an offset indicator. If you want a local date without an offset indicator, simply use a format without an offset:
moment.utc("20:00", "HH:mm").format('YYYY-MM-DDTHH:mm:ss.SSS')
"2016-09-08T20:00:00.000"
If you are dealing with local dates that do not have a time zone association, I recommend using moment.utc to parse, as this will ensure that the time does not get shifted to account for DST in the current time zone.
For more information about how to parse dates into the time zone or offset that you would like in moment, see my blog post on the subject.
This it how it should look:
var a = moment("20:00", "HH:mm")
console.log(a.utcOffset('+0000').format())
<script src="http://momentjs.com/downloads/moment.min.js"></script>
Doe, the problem is that you are using timezones when you create the date.
MomentJS uses your current timezone automatically.
Mongo however saves the time as it would be in another timezone.
Therefore, if you want the two strings to format the same way, you need to set the timezone.

How do you preserve a JavaScript date's time zone from browser to server, and back?

For example, using a date and time control, the user selects a date and time, such that the string representation is the following:
"6-25-2012 12:00:00 PM"
It so happens that this user is in the EST time zone. The string is passed to the server, which translates it into a .NET DateTime object, and then stores it in SQL Server in a datetime column.
When the date is returned later to the browser, it needs to be converted back into a date, however when the above string is fed into a date it is losing 4 hours of time. I believe this is because when not specifying a timezone while creating a JavaScript date, it defaults to local time, and since EST is -400 from GMT, it subtracts 4 hours from 12pm, even though that 12pm was meant to be specified as EST when the user selected it on a machine in the EST time zone.
Clearly something needs to be added to the original datetime string before its passed to the server to be persisted. What is the recommended way of doing this?
Don't rely on JavaScript's Date constructor to parse a string. The behavior and supported formats vary wildly per browser and locale. Here are just some of the default behaviors if you use the Date object directly.
If you must come from a string, try using a standardized format such as ISO8601. The date you gave in that format would be "2012-06-25T12:00:00". The easiest way to work with these in JavaScript is with moment.js.
Also, be careful about what you are actually meaning to represent. Right now, you are passing a local date/time, saving a local/date/time, and returning a local date/time. Along the way, the idea of what is "local" could change.
In many cases, the date/time is intended to represent an exact moment in time. To make that work, you need to convert from the local time entered to UTC on the client. Send UTC to your server, and store it. Later, retrieve UTC and send it back to your client, process it as UTC and convert back to local time. You can do all of this easily with moment.js:
// I'll assume these are the inputs you have. Adjust accordingly.
var dateString = "6-25-2012";
var timeString = "12:00:00 PM";
// Construct a moment in the default local time zone, using a specific format.
var m = moment(dateString + " " + timeString, "M-D-YYYY h:mm:ss A");
// Get the value in UTC as an ISO8601 formatted string
var utc = m.toISOString(); // output: "2012-06-25T19:00:00.000Z"
On the server in .Net:
var dt = DateTime.Parse("2012-06-25T19:00:00.000Z", // from the input variable
CultureInfo.InvariantCulture, // recommended for ISO
DateTimeStyles.RoundtripKind) // honor the Z for UTC kind
Store that in the database. Later retrieve it and send it back:
// when you pull it from your database, set it to UTC kind
var dt = DateTime.SpecifyKind((DateTime)reader["yourfield"], DateTimeKind.Utc);
// send it back in ISO format:
var s = dt.ToString("o"); // "o" is the ISO8601 "round-trip" pattern.
Pass it back to the javascript in moment.js:
// construct a moment:
var m = moment("2012-06-25T19:00:00.000Z"); // use the value from the server
// display it in this user's local time zone, in whatever format you want
var s = m.format("LLL"); // "June 25 2012 12:00 PM"
// or if you need a Date object
var dt = m.toDate();
See - that was easy, and you didn't need to get into anything fancy with time zones.
Here, I think this is what you are looking for:
How to ignore user's time zone and force Date() use specific time zone
It seems to me that you can do something like this:
var date = new Date("6-25-2012 12:00:00 PM");
var offset = date.getTimezoneOffset(); // returns offset from GMT in minutes
// to convert the minutes to milliseconds
offset *= 60000;
// the js primitive value is unix time in milliseconds so this retrieves the
// unix time in milliseconds and adds our offset.
// Now we can put this all back in a date object
date = new Date(date.valueOf() + offset);
// to get back your sting you can maybe now do something like this:
var dateString = date.toLocaleString().replace(/\//g,'-').replace(',','');
Blame the JSON.Stringfy()... and do:
x = (your_date);
x.setHours(x.getHours() - x.getTimezoneOffset() / 60);
I am using a filter before sending the date to the server:
vm.dateFormat = 'yyyy-MM-dd';
dateToSendToServer = $filter('date')(dateFromTheJavaScript, vm.dateFormat);

Categories

Resources