I am currently using angular 9 DateTime Pipe in order to format my dateTimes.
I am storing the dateTimes in database with DataTimeOffset.
When I am retrieving this dates from server are in this form: "2021-03-30T16:26:52.047+02:00"
I am using this code to apply the format to my dates:
const pipe = new DatePipe('en-Us);
const formatedDate = pipe.transform(date, 'dd.MMM.yyyy HH:mm:ss');
When I am doing this, the pipe is taking the browser time and format my date.
I know that this is the default option, if I am not sending the 3rd parameter to the transform function.
But I have a business need to show the dates as they are...but formatted in the format mentioned above,
My question is: How can I avoid the timeZone convert but still format the dateTime?
You may use var transformedDate = new Date(datepipe.transform(myDate, 'yyyy-MM-dd' + ' UTC'))
After many days of investigation, the only workaround was to use the library "Luxon".
https://moment.github.io/luxon/docs/manual/zones.html
With this library I can do something like this:
var keepOffset = DateTime.fromISO("2017-05-15T09:10:23-09:00", { setZone: true });
Which will keep the offset intact.
Related
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.
Im new to momentJs so I need a bit of help here. I am building a form where the user can send in their availabilities for a certain work period. So in the form you have a startDate, startTime, endDate and endTime. Due to the api that I have to use from a client we have to send the date like this (example) "2015-06-17T14:24:36" (with the 'T' in the middle). Currently I receive the date and the time seperate from eachother but merging them together in the end so it fits the api's way of reading date.
Now my question is as follow. I have to create a check where I can see if the input startdate-time and enddate-time are valid. For example the startdate always has to be a date BEFORE the end date (pretty logic right). But is there an easy way to do this in momentJS?
Or should I use another method?
Thanks in regard and if my question is not quite clear please let me know so I can provide extra information!
NOTE: in the end it should be something like this:
var start = "2017-06-17T14:24:36"
var end = "2017-07-03T14:24:36"
Function that checks if the start and end dates are valid
Result = true
If you simply have to check that startDate is before endDate you can use isAfter.
Here a working sample:
var start = "2017-06-17T14:24:36";
var end = "2017-07-03T14:24:36";
function checkDate(start, end){
var mStart = moment(start);
var mEnd = moment(end);
return mStart.isBefore(mEnd);
}
console.log(checkDate(start, end));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
In my first example I'm using moment(String) parsing that accepts input in ISO 8601 format.
If you need to parse non ISO 8601 format you can use moment(String, String) specifying input format (e.g. var mStart = moment(start, 'DD-MM-YYYYTHH:mm:ss');).
If you have to support multiple formats you can use moment(String, String[]). As docs states moment(String, String[]):
Prefer formats resulting in valid dates over invalid ones.
Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.
Prefer formats earlier in the array than later.
I am trying to convert a client date / time string on a form into a JSON date / time string using JavaScript and moment (for a Django REST API back end). Here is what I have so far:
document.getElementById("dt_tm").value =
moment(document.getElementById("inp-st").value, "DD/MM/YYYY HH:mm").toJSON();
Two problems with this:
The date format cannot be hard coded as the client may have a different date format,
moment adjusts the date / time and I don't need it to do that because the back end performs that function (using Django time zones).
So for example:
moment("14/05/2016 18:00", "DD/MM/YYYY HH:mm").toJSON() =
"2016-05-14T17:00:00.000Z"
When what I need is:
"2016-05-14T18:00"
(In this example my time zone is currently GMT+1.)
If you would like toJSON to return the date in a different format, redefine moment.fn.toJSON to that it returns with your custom format instead of the default ISO8601 date format. This is outlined in the documentation.
moment.fn.toJSON = function() {
return this.format("YYYY-MM-DDTHH:mmZ");
};
Our previous developer create a generic method that retrieve all user input that has an update/changes.
it looks like this (user side/JavaScript/Kendo):
param._updated = JSON.stringify(rows._updated);
I am somehow desperate that when that *rows._updated contains a Date Value uncle JSON convert it into other String format that result to DateTime Difference for example:
dateField = 11/1/2015 // <--Original User Input
rows._updated = { dateField: November 1, 2015 0:00:00 GMT+080 ... }
param._updated = { "dateField": "2015-10-31T16:00:00.0000Z"... }
which would now result to a conflict.
since the above code was generic field that might contain different data and type, I am trying to solve this issues at the server side but i failed to achieve the original date value.
NOTE: our users has 2-5 different timezone so it's kinda hard to hard code the conversion.
related issues: here
It's getting late. Thanks in advance!.
I somehow achieve what I want to by the following approach
1.) At backend Convert the DateTime to UTC Format
string dateUTC = paramDate.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
2.) Now I have created a method that will handle the convertion of UTC Date to PlainDate
public static string UTCtoPlainDate(string dateUTC)
{
if (string.IsNullOrEmpty(dateUTC)) return "";
DateTime dateTime;
// Assume date in UTC format, e.g. '2015-03-31T12:00:00.000Z'
DateTime.TryParseExact(dateUTC, "yyyy-MM-dd'T'HH:mm:ss.fff'Z'", System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeUniversal, out dateTime);
return dateTime.ToString("yyyy-MM-dd") ?? "";
}
I need to show date in the same timezone as it coming in from service. But angular date filter converts the date to local timezone. is there a way to avoid conversion in local timezone.
My input is 2014-12-11T05:21:22.323-05:00
required output - 12/11/2014 05:21:22 PM (without converting to local timezone)
Thanks in advance.
You can create a custom filter for this, just convert the desired date without the timezone, for example:
myApp.filter('ignoreTimeZone', function(){
return function(val) {
var newDate = new Date(val.replace('T', ' ').slice(0, -6));
return newDate;
};
});
Check this fiddle:
http://jsfiddle.net/ghxd6nom/
You can also use a library for this, like moment.js
Angular provides service '$filter'. We can inject this service on controller.
with the help of this service, we can format the date .
var dateFrom = $filter('date')(new Date(), "MM/dd/yyyy");
in this way, we can able to format the date with or without Timezone.
The return valus is string and we can convert the string into DateTime on Backend.
The otherway is to use library moment.js.
This library provides better way of converting/formatting Dates.
check this blog , which provides angular date/time filtering & formatting.
You can use this :
$filter('date')(date, format, '+0000')
Documentation: https://docs.angularjs.org/api/ng/filter/date