I have a date string const someDate = 2023-02-13T09:00:00.000-05:00
The problem is when I'm formatting it via dayjs
dayjs(someDate).format('h:mm A')
It returns me string according to my local timezone, when I need to keep like I received.
Any way to disable converting time to local timezone in dayjs?
Yes!
You can disable converting to local timezone in dayjs by passing in the original timezone as an additional argument in the dayjs constructor.
Example:
const someDate = "2023-02-13T09:00:00.000-05:00";
const originalTimezone = someDate.slice(-6);
const formattedDate = dayjs(someDate).utcOffset(originalTimezone).format('h:mm A');
The utcOffset() method allows you to set the offset in minutes from UTC for a specific date instance. The originalTimezone constant is used to extract the timezone offset (-05:00) from the original date string someDate, and pass it to the utcOffset() method. This will ensure that the formatted date stays in the original timezone.
Related
Hello I have a function which converts a local time to UTC using the local timezone and date:
this.conversion.dateTimeToTime('2022-07-04 12:30', 'America/Los_Angeles');
public dateTimeToTime(date, timezone = 'UTC') {
date = new Date(date);
return date.toLocaleTimeString('en-GB', {timeZone: timezone, hour12: false});
}
}
this is 12:30 local to UTC which should be 20:30(ish) but the output is 4:30utc instead going backwards
I am wondering what I am doing wrong
Thanks
Keeping date as simple date string(2022-01-31) causes data loss in JS and providing it to Date constructor can result in wrong date. Check this SO question for more.
Generally I convert my date to ISO format by using Date.toISOString. Next when I want to parse it as JS Date object, I use parseISO method of date-fns.
Here is a CodeSandbox example: https://codesandbox.io/s/summer-bush-iv0h2g?file=/src/index.js
I have used moment-tz instead:
import * as moment from "moment-timezone";
let blah = moment.tz("2019-06-03 12:30", "America/Los_Angeles");
console.log(blah.format());
console.log(blah.clone().tz("UTC").format());
I am converting a timestamp on a DB object using moment:
{moment(comment.created_at).local(true).format('h:mm a')}
My time is outputting in UTC time because that is how it gets created in my DB.
So I am seeing '6:45 PM' for example, when I want to see the time in MY timezone (EST) or the user's relative timezone. According to the moment docs local() will convert to your current timezone? Calling the local() method as shown in my code aboven does not change the time zone. Am I using this incorrectly?
My DB object
{
client_id: 24
created_at: "2022-02-11 17:41:39.330443"
id: 22
report: "sfsf"
report_category: "Client Assigned"
volunteer_id: 23
}
Your database is storing the date without an offset indicator. This means that moment cannot automatically determine the timezone. As per the documentation on parsing dates:
moment(...) is local mode. Ambiguous input (without offset) is assumed to be local time. Unambiguous input (with offset) is adjusted to local time. * moment.utc(...) is utc mode. Ambiguous input is assumed to be UTC.
So if you know your input is UTC and you know it won't have an offset indicator, use moment.utc() instead of moment().
Furthermore, you don't want to use local(true), since passing in "true" will only change the timezone on the object without changing the time (see the documentation). So you're left with:
{moment.utc(comment.created_at).local().format('h:mm a')}
I converted your DB timestamp into ISO format and then passed into your implementation
let t = "2022-02-11 17:41:39.330443"
let utcISOTimestamp = moment.utc(t).toDate()
console.log(utcISOTimestamp)
//let res = moment(utcISOTimestamp).local(true).format('h:mm a');
let res = moment(moment.utc(t).toDate()).local(true).format('h:mm a');
console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Try using:
moment.utc('2022-02-11 17:41:39').local().format('YYYY-MM-DD HH:mm:ss')
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 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.
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" />