Is it possible for Momentjs to display the localtime and autoformat the string.
I have eg. the time 2015-03-20T09:08:53+01:00 and want momentjs to display in local time and format this in danish starting DD-MM-YYYY
$('[data-momentdate]').each(function () {
var localTime = moment.utc($(this).attr('data-momentdate')).toDate();
localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
$(this).html(localTime);
});
The above code converts the utc time to local danish time, but I want momentjs to determine which format to use based by the timezone
Any ideas ?
Lets say you have a UTC date-time string as 2014-02-19 05:24:32 AM and you want to determine time in your timezone then use following code:
moment.utc('2014-02-19 05:24:32 AM').toDate();
toDate() method gives javascript Date() object.
$(function(){
setInterval(function(){
var divUtc = $('#divUTC');
var divLocal = $('#divLocal');
//put UTC time into divUTC
divUtc.text(moment.utc().format('YYYY-MM-DD HH:mm:ss'));
//get text from divUTC and conver to local timezone
var localTime = moment.utc(divUtc.text()).toDate();
localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
divLocal.text(localTime);
},1000);
});
For more information look at: How to get local time from UTC using Moment.JS.
Update:
By default, moment parses and displays in local time. If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment().
moment().format(); // 2013-02-04T10:35:24-08:00
moment.utc().format(); // 2013-02-04T18:35:24+00:00
On the other hand, there maybe different format for one timezone and in that case you should give the format. In addition to this, if you want to use the same format you can use globalization property as below on the web.config:
<system.web>
<globalization culture="de-DE" uiCulture="de-DE" />
Related
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.
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.
I have a date format is GMT or UTC.
var mydate = '2020-01-14T17:43:37.000Z'
I want to convert this date in IST format so according to this date the output I need in this format.
var date = '2020-Jan-15 12:45'
You can specify an IANA time zone identifier in the options passed to toLocaleString. The identifier for India is Asia/Kolkata.
var s = new Date('2020-01-14T17:43:37.000Z').toLocaleString(undefined, {timeZone: 'Asia/Kolkata'});
This will do the correct time zone conversion, as the input is in UTC (as specified by the Z at the end).
undefined means to use the user's locale for the formatting of the date and time. This is usually what you want. If you want a more particular format (like what you specified in your question), you can provide a specific locale string and/or adjust the other options for toLocaleString, as given in the docs.
Also, note that the conversion in your question is incorrect. India is 5 hours an 30 minutes offset from UTC. Thus the correct output is 2020-01-14 23:13:37 (in whatever format you like)
Another option for you is to use the moment and moment timezone modules for timezone conversion, they are very flexible and you can format the resulting date object according to whichever format you wish.
As mentioned by #matt-johnson-pint (thank you!) you can also use the very cool Luxon library for this purpose, I've added an example below.
const mydate = "2020-01-14T17:43:37.000Z"
// Create a UTC date object. The moment constructor will recognize the date as UTC since it includes the 'Z' timezone specifier.
let utcDate = moment(mydate);
// Convert the UTC date into IST
let istDate = moment(mydate).tz("Asia/Kolkata");
console.log("Using Moment.js:");
console.log(`UTC date (iso): ${utcDate.format("YYYY-MM-DD HH:mm:ss")}`);
console.log(`IST date (iso): ${istDate.format("YYYY-MM-DD HH:mm:ss")}`);
const DateTime = luxon.DateTime;
utcDate = DateTime.fromISO(mydate);
istDate = DateTime.fromISO(mydate).setZone("Asia/Kolkata");
console.log(`\nUsing Luxon:`);
console.log(`UTC date (iso): ${utcDate.toFormat("yyyy-LL-dd HH:mm:ss")}`);
console.log(`IST date (iso): ${istDate.toFormat("yyyy-LL-dd HH:mm:ss")}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-1970-2030.js"></script>
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>
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.
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.