Convert all date/datetime elements to local timezone - javascript

how to convert all elements with date/datetime string to display in users local timezone in javascript(jquery, moment or anything). all datetime text with classname to localtime zone using jquery or moment.js or any javascript methods.
In https://momentjs.com/timezone/ there is a timezone method. but how can we do it in one method

What I would do is make sure that the server returns datetime in ISO 8601-format per here:
Then you can use that datetime or get all elements with appropriate class associated with it using javascript or jquery.
Javascript for converting UTC DateTime to local user's DateTime
var utcDateTime = '2019-05-15T08:33:48.000Z'; // ISO-8601 formatted date returned from server
var localDateTime = new Date(utcDateTime);
The localDateTime will be in the right local time which in my case would be three hours later (GR time).
jQuery to change val of said elements
$('.yourDateclass').each(function() {
$(this).val(localDateTime);
});

Related

How to add time zone to specific format in momentjs?

I am trying to get specific format of datetime with time zone
i am getting string of time format which is shown below
var dateTime = "2020-06-01T01:50:57.000Z CDT"
I need to convert the format in to
const offsetTime = moment(date).add("-0.00", 'hours')
const formatedDate = moment(offsetTime, 'h:mm:ss A')
.utc()
.format('h:mm A')//(1:50 AM)
Required output
(1:50 AM CDT)
Do i need to split the string and get the format or do we have any method to convert it to this format in momentjs
In simple way to say
YYYY-MM-DDTHH:mm:ss.SSS[Z] z To hh:mm A z //format
and if the string contains only 2 character like "CT" instead of CDT how to capture that.
You can zz to get timezone in output. For ex:
moment()..format('h:mm A zz')
More documentation here momentJS
Use the moment-timezone to achieve this. Use the moment constructor to specify the input format, then specifying the required timezone. Finally use moment's format to get the required format
var dateTime = "2020-06-01T01:50:57.000Z CDT";
var timezone = "America/Chicago";
console.log(
moment(dateTime, "YYYY-MM-DD hh:mm:ss zz")
.tz(timezone)
.format("h:mm A zz")
);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
Your date string is in ISO format with the 'Z' after seconds indicating that it is in UTC time. I am assuming that the 'CDT' is placed in the string in order to indicate which time zone this should be converted to. If you have control over how this string is represented then I recommend changing it so that you indicate the desired timezone elsewhere and simply store the date in UTC format. This way you can initialize a date or moment object with the ISO string as follows:
var date = moment("2020-06-01T01:50:57.000Z")
It is inconvenient the way it is currently since you cannot initialize it this way:
var date = moment("2020-06-01T01:50:57.000Z CDT")
The only option for handling the date in its current form is to parse it. You can do that like this:
var dateTime = "2020-06-01T01:50:57.000Z CDT"
var trimmed = dateTime.trim() // remove leading and trailing whitespace
var isoString = trimmed.substr(0, trimmed.indexOf(' '))
Which will produce the following string
2020-06-01T01:50:57.000Z
You can use that string I called "isoString" to initialize a date or moment object. The next obstacle is to handle converting that UTC string to a certain timezone (in this case CDT). It is simple if you want to convert the UTC date to the current users timezone since that will happen automatically when you initialize the moment or date object with the ISO date string. Otherwise, you need some way to get the timezone from 'CDT' into the format moment wants which was shown by #vjr12 ("America/Chicago"). The only way to do this is to either store that with the date string or create a mapping. It is much easier to convert from "America/Chicago" to "CDT" than it is to convert from "CDT" to "America/Chicago". Your only option with the current form is to create your own mapping from "CDT" to "America/Chicago". You could do something like:
let tzMap = new Map()
tzMap.set('CDT','America/Chicago')
// Set the rest of your timezones
You would need to do that for all timezones and then you could use the timezone parsed from your date string like this:
var tzAbbr = trimmed.substr(trimmed.indexOf(' ') + 1)
which will grab the "CDT" or "CT" for that matter. Then you could use your mapping like this:
var timezone = tzMap.get(tzAbbr)
timezone will be "America/Chicago" in this case and then you can use #vjr12 solution from here to get the form you want.
Note
I highly recommend that (if you are able) to change the current format of the datestring that you are using. The purpose of using UTC time is to be timezone agnostic so it does not make sense to store the timezone with the UTC string. If you want to preserve the timezone then you would be better off using a format which already embeds the timezone.

Converting a DateTime Object to a specific timezone

I have a dateTime string "2019-02-14 17:18:22".
I would like to convert this above-mentioned dateTime string to a specific timezone dateTime .
Here the timezone will be extracted from another dateTime string - "2019-02-14T17:28:24+08:00".
I did look up at the utcOffset function but I don't know how to use the offset value (330 in mycase).
Expected result: The first String is fairly simple 5:18 PM .
But once getting converted to the specific timezone, it will be 2:48 PM.
Heres how I use timezone offsets.
I get DateTimeIn, which is offset to (UTC+00:00) from the server.
Then to convert to the browser's timezone (UTC-05:00), i use: getTimezoneOffset() to update the object to the local timezone.
var dateObj = new Date(DateTimeIn);
dateObj.setMinutes(dateObj.getMinutes() + dateObj.getTimezoneOffset());
Without this, my server downloaded datetimes are offset and unusable.

Return date and time in ("YYYY-MM-DD HH:mm") format when using moment.js (timezone)

I am using moment-timezone so I can convert from selected timezone to timezone of a client.
I wasn't able to implement it in a better way than this:
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 convertedTime = this.$rootScope.mtz.tz(utcTime, timeZoneInfo.usersTimeZone).format("Z");
return convertedTime;
}
So basically I am using usersTimeZone: this.$rootScope.mtz.tz.guess(), guess() function to find out timezone from the browser.
Then I get values from datetime picker and dropdown and convert them to UTC value by using utcOffset.
At the end I want to convert that utc value to user timezone value.
I get object like this:
_d represent correct value after conversion. I have tried adding bunch of different .format() paterns on convertedTime variable, but I am not able to retrive time in this format: "YYYY-MM-DD HH:mm". I guess it works differentlly than when using .utcOffset() function.
Can anybody help me with this?
You don't need to guess the client time zone to convert to local time. Just use the local function.
For example:
moment.tz('2016-01-01 00:00', 'America/New_York').local().format('YYYY-MM-DD HH:mm')
For users located in the Pacific time zone, this converts from Eastern to Pacific and you get an output string of "2015-12-31 21:00". For users in other time zones, the output would be different, as expected.
You don't need to format to a string and re-parse it, or manually manipulate the UTC offset either. That is almost never warranted.

asp.net mvc datetime dynamic validation by clients date format

I have a Custom Attribute for DateTime validation with given dateformat and also javascript validator which are provide me both client side and server side validation. But now I should change my datetime validation so that it would be performed according clients local DateTime format and I do not know how.
I couldn't find anything that help me.
So please advise me how can I implement at least client side DateTime validation or how can I get client's date format by javascript.
If you can determine the locale of your user, you can use .Net globalization classes to assist with server-side parsing of date time strings. For example:
// Parsed as January 4th
var dt1 = DateTime.Parse("1/4/2013", new CultureInfo("en-US"));
// Parsed as April 1st
var dt2 = DateTime.Parse("1/4/2013", new CultureInfo("en-GB"));
But the best thing to do is avoid this entirely. In your JavaScript code, get the value back as an ISO8601 string - which is culture invariant. Native browser support for this varies. The built-in functions work in IE9+.
// This returns an ISO formatted date, in UTC.
var s = yourDate.ToISOString();
One way to get full browser support, and get an ISO date without converting to UTC, is to use the moment.js library, where ISO8601 is the default format:
// This returns an ISO formatted date, with the user's local offset.
var s = moment(yourDate).format();
// This returns an ISO formatted date, in UTC.
var s = moment(yourDate).utc().format();
When you send these values to the server, you can parse them in your .Net code without concern for culture. The format is already culture invariant. To prevent the server's time zone from interfering, you should parse them as a DateTimeOffset:
// assuming this is an ISO value you got from the client:
var s = "2013-04-20T09:00:00-07:00";
// simply parse it
var dto = DateTimeOffset.Parse(s);
// if you don't care about the offset at this point:
var dt = dto.DateTime;
Of course, if you want to fail gracefully, you can do this instead:
DateTimeOffset dto;
var isValid = DateTimeOffset.TryParse(s, out dto);

jQuery / Javascript - convert datetime to user's timezone datetime

I updated this question
I would like to transform a datetime to the equivalent datetime in the country(timezone) user is located to.
I have datetime in this format which is UTC/GMT:
Oct 31, 2012 08:10:02
now, according with the user's client timezone i would like to convert that datetime using the current browser/client user's timezone
how can i do that?
If I understand correctly, you want to be able to set the end date for the countdown in UTC time, as opposed to the local time of the browser. You don't need to modify the plugin to do this. You just want the setUTC... methods in the Date object. Take a look here: http://www.w3schools.com/jsref/jsref_obj_date.asp.
For example:
var endofworld = new Date(0);
endofworld.setUTCFullYear(2012);
endofworld.setUTCMonth(11);
endofworld.setUTCDate(21);
$('.countdown').countdown({ date: endofworld });

Categories

Resources