Datetime in MST Zone - javascript

On ASP.net MVC application where I save the date on datetime field in SQL sever db.It saves like this 2015-04-22 18:43:18.967.So now I need to show it as MST (Mountain Standard Time) on client side.So how can I do that ? I can use Moment.js or any other JavaScript library for that.Thanks in advance.

If you send the timestamp to the client and you are using momentjs, then it's pretty simple
var day = moment(TS_IN_MILLISECONDS).tz('America/Denver')
With the string you provided, you can do this:
var UTCTime = moment.utc('2015-04-22 18:43:18.967').toDate();
var MSTTime = moment(UTCTime).tz('America/Denver').format('YYYY-MM-DD HH:mm:ss');

So this will depend on what local time your server is running in (or if it's just pulling UTC it'll be a bit easier). But you can yank the timezone offset like this: dateTime.getTimezoneOffset(), modify it it to reflect the offset difference between your server's timezone and MST. And then modify your original datetime to reflect the new offset.
This may be a good post for reference.
Also refer to here:
dateTime.setTime( dateTime.getTime() + dateTime.getTimezoneOffset()*[math to adjust your timezone] );

Related

Javascript translate date in a given timezone to local date

In Javascript, given a string representing a date like this one:
var dateFromPrague = "2011-10-10T14:48:00"
And knowing above date is a date from a specific localization, like Europe/Prague, how could I get this date translated to the local hour? I know I can create a Date object indicating timezone offset like this:
var dateFromPrague = new Date("2011-10-10T14:48:00.000+02:00");
Then I could get local date from above date like this:
var dateFromPragueTolocalDate = dateFromPrague.toString();
But Prague offset is not always +02:00 as it depends on DST being applied or not (summer or winter hours). So How could I indicate the right timezone, something like 'Europe/Prague', or achieve this translation some way (returning offset from server is not possible)?
There isn't currently anything built into JavaScript itself (or the browser platform) that lets you do this, no, you're in the land of libraries. In a couple of years you'll probably be able to use Temporal, but it's still at an early stage in the proposals process. There's a polyfill linked from the proposal, but the part you'd want to use would probably be the provisionally-named LocalDateTime (not its final name) which is still a work in progress.
One library that you can do this with is Moment Timezone. That looks like this:
var a = moment.tz(dateFromPrague, "Europe/Prague");
Live Example:
var dateFromPrague = "2011-10-10T14:48:00";
var a = moment.tz(dateFromPrague, "Europe/Prague");
console.log(a.toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data.min.js"></script>
You should get the dates in UTC from server and then you can use date.toLocaleDateString() to convert to local date. This is the typical approach.

Preserve Local DateTime in Javascript

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.

How to get client side timezone id in JavaScript?

I need to get client side timezone using JavaScript. I am using below code.
new Date().toString().split('(')[1].slice(0, -1)
But it returns timezone daylightname, and I need id.
For example, client side timezone as set as (UTC-05:00) Eastern Time (US & Canada) and I need to get output as Eastern Standard Time. But I am getting Eastern Daylight Time as output.
Can I do this without any additional plugin requirements?
Try the following
var objdatetime = new Date();
var timezone = objdatetime.toTimeString();
var tzstr = timezone.split("(");
var timezoneid = tzstr[1].toString().replace(")","");
alert(timezoneid);
How about this?
new Date().toString().split('(')[1].slice(0, -1).replace('Daylight', 'Standard')

Microsoft AJAX serialized dates with time swift

I have an MVC 3 web application for a web API, a controller emit json.
In the json result I see dates are being serialised automatically
as
{
Flag: "U"
EventId: "168ef1d4-60ca-4fa1-b03b-8c3207650347"
EventTitle: "test event 11"
DateTimeStart: "/Date(1369217469310)/"
IsCustomEvent: true
Location: null
}
in javascript I need to convert DateTimeStart in human readable format and using this code
var date = new Date(1369217469310);
alert(date);
I see the resulting data as
Wed May 22 2013 12:11:09 GMT+0200 (CEST)
This is 1 hour a head of the date stored in the application wich is 22/05/2013 11:11:09.
I would like to know where the issue could be and how to fix it:
Is it .Net serialising dates by default using CEST wich is +1 UCT, in this case how to set up UCT at 0?
Is it an issue when converting in the date using JavaScript?
Please let em know how you would fix it, thanks!
I haven't enough information to advice about the server side. Generally the source of the problem on server side may be the CultureInfo set in you application. You may consider to convert all datetimes as UTC before sending it to the browser. Check the DateTime.ToUniversalTime() method.
On client side you also are able to fix the offset between regional time and UTC. There is no build in function to do this, but it's very simple operation to perform. Check the code below.
var date = new Date();
var dateWithOffset = date.getTime() + date.getTimezoneOffset() * 60000;

Display Browser specific date/time using extjs

I have a database field called CreatedDate which is a timestamp field and holds the date and time. It currently holds the GMT time.
At the moment this field is displayed as it is on the web pages.
We want to amend this to show date/time as per browser local time zone
Can you please let us know how we can do this.
Thanks in advance
If you can represent the universal time as a count of milliseconds since the 1 Jan 1970 epoch at the server then you can have the page code construct Date instances at the client using the client time zone, but starting from that UTC reference. It's the normal behavior of the Javascript Date() constructor:
var clientDate = new Date(serverUTC);
Now exactly how you get that UTC value depends on your server language. In a JSP page it'd be pretty simple:
var clientDate = new Date(<%= whatever.getTheDate().getTime() %>);
or
var clientDate = new Date(${something.theDate.time});
Once you've got the date value as a client-side Javascript Date instance, you can just update the field(s) with the string. There are no built-in Date formatting tools, but the old standard date.js might help with its ".toString()" formatter.

Categories