Format date/time using local time zone - datetime

In Flutter I need to parse and format date/time based on what my REST API passes back. The date/time format the server sends back is 2020-01-28T13:52:30.878+0000. In this example based on my locale it should be formatted as 8:52:30 AM EST. Does anyone know how I can achieve this using either a standard Dart package or some third-party package?

Just figured it out, using DateTime class there is a method toLocal() that does exactly what I need.

You can use DateTime.parse("2020-01-28T13:52:30.878+0000") to parse this format.
if GMT+5
formatedTime = DateTime.parse("2020-01-28T13:52:30.878+0000");
farmattedTime.add(Duration(hours: 5));

Related

Date parsing errors when timezone does not exist with Java OpenAPI generator client

I'm working on integrating with an API that (unfortunately) does not always append the timezone offset to their date. I know this isn't optimal but I can't change their behavior.
Example:
2022-06-08T16:07:13.96
Using the java generator and the java8 date library produces a runtime error while parsing the date:
java.time.format.DateTimeParseException: Text '2022-06-08T16:07:13.96' could not be parsed at index 22
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2052)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1954)
at java.base/java.time.OffsetDateTime.parse(OffsetDateTime.java:404)
at com.acme.openapi.JSON$OffsetDateTimeTypeAdapter.read(JSON.java:287)
From my limited understanding, I believe that ISO-8601 dates should be treated as local dates instead of offset dates if the zone offset is omitted. Im unsure if this is something that is supported in the java generator.
I ended up swapping the date library to java8-localdatetime but it gave GSON some problems:
Expected BEGIN_OBJECT but was String
I changed to a jackson based client and that cleared everything up.
I use this nasty wrapper everywhere, where I use a DateTime from the API, to "hack" it in the current timezone.
DateTime utcHack(DateTime dt) {
return DateTime.parse(dt.toLocal().toString() + "Z");
}
I am open for improvements!

How can I get SignalR to stop changing my date/time values?

I have a simple class that contains a DateTime property. When I set the value of this property using DateTime.Now() the value is correct. However, when I pass this class object as a parameter via SignalR, on the receiving end SignalR has changed the DateTime so that it no longer matches the original DateTime. How can I get SignalR to stop manipulating my DateTime values? This issue seems to have started with a recent update to the latest SignalR nuget packages.
This seems to be a problem when the hub and the client are in two different time zones. It seems Microsoft is trying to help, by adjusting the date/time to the local time zone, but I want the original value, not the value Microsoft "thinks" I want.
When you want two systems to communicate with each other I would recommend using always the DateTime in UTC for various reasons. In your case you have two options here:
1 - Send the date as string string date = DateTime.Now.ToString(CultureInfo.InvariantCulture); so on the client side you just need to parse the datetime like DateTime.Parse(date, CultureInfo.InvariantCulture);.
2 - Send the date in UTC like DateTime.UtcNow; so event if the SignalR tries to change the date, it will have the DateTime.Kind as UTC. In this case or you will get the current date correctly, or you just adjust on the client side to the local time like receivedDate.ToLocalTime();
This one was a real head scratcher as I had the exact same issue. The client was storing the correct time but by the time it hit the Hub... it had changed. I'm really glad you posted this as I wouldn't have imagined this issue being possible. #Kiril1512 posted the correct resolution. In my case I used his second option as I didn't want to change my model... although simply converting to a string would have been simpler. While I did follow his suggestion and convert everything to DateTime.UtcNow()... I am thinking this was unnecessary as I noticed even previously stored dates converted correctly. This makes me think that either this isn't necessary to do, or dates are converted to Utc when they hit the Hub automatically which may be what the issue was to begin with?
Either way I posted this as I discovered that converting this date back to Local time was a little more involved. Here is how I ended up doing the conversion which resolved this issue for me that I gathered from this resource:
DateTime convertedDate = DateTime.SpecifyKind(
DateTime.Parse(msg.CreatedOn.ToString()),
DateTimeKind.Utc);
var kind = convertedDate.Kind;
DateTime dt = convertedDate.ToLocalTime();

Display a FrozenTime object in ISO_8601 while converted to a timezone

I have a Cake\I18n\FrozenTime object that I need displayed both as 2020-09-11T04:15:44+00:00 and converted to a specific timezone.
Normally, I'd call ->format('c'), but that uses the UTC according to my app configuration.
I know I can convert to a timezone using ->i18nFormat('yyyy-MM-dd HH:mm', 'Europe/Copenhagen'), but then I'll lose the convenience of the c date format shorthand. IntlDateFormatter predefined constants are lacking, and those from DateTimeInterface, (specifically, \DateTime::ATOM) don't work.
So before I go ahead and reinvent the wheel with ->i18nFormat("yyyy-MM-dd'T'HH:mm:ssxxx", 'Europe/Copenhagen'), is there a better way to display a Cake\I18n\FrozenTime in a specific date format and a specific timezone?
If you want to keep a date object, you can simply apply the timezone conversion on the object.
Frozen* objects are immutable, so you'll end up with a new object when applying the conversion:
echo $obj->setTimezone('Europe/Copenhagen')->format('c')
See also
Chronos API > \Cake\Chronos\ChronosInterface::setTimezone()

how to get default timezone time in moment timezone

I am using moment timezone to set default time
$moment.tz.setDefault('Europe/London');
$moment().toString();
is providing me the time in the defined timezone. but I need the timestamp. so I am using
$moment().now();
but it's returning the timestamp in local timezone. how can I get the timestamp of the default timezone(Europe/London)?
Moment.now is not really a public api. It is intended to be used for testing purposes only. All that you want to do is format a moment, so your code would be as follows:
moment.tz.setDefault('Europe/London');
moment().format(); //"2016-10-18T21:57:39+01:00"

Specify datetime format for WCF Data Service

Is there a way to specify the formatting of DateTime data returned by a WCF data service?
This question seems to say that the default format, which looks like /Date(1339515455030)/, is the number of milliseconds since midnight Januery 1, 1970 UTC. I can figure out how to parse that if I have to but I'd rather specify a more friendly format.
The OData DateTime format (assuming you haven't already formatted it out to a string) is dependent on the wire format negotiated between client and server. The format above is from JSON Verbose and corresponds to a standard JavaScript Date object. The Atom format is different, and JSON Light is different still. Of special note is that we decided to move away from the traditional JavaScript Date format in favor of ISO 8601 for JSON Light. In any of these cases, if you're using a client such as the WCF DS client or data.js, the client will take care of deserializing the value properly.
Atom formatted date: <d:OrderDate
m:type="Edm.DateTime">1996-07-04T00:00:00</d:OrderDate>
JSON verbose formatted date: "OrderDate":"\/Date(836438400000)\/"
JSON light formatted date: "ShippedDate":"1996-07-16T00:00:00"
For current client libraries on a variety of platforms, see here: http://www.odata.org/libraries
With OData V3 the JSON Verbose format uses the ISO 8601 which seems to be more friendly to some consumers. Note though that it will only be used if the payload is V3. So you will need to update your server side to supper OData V3 (if it's WCF DS, then you want to use the WCF DS 5.0 release which can be found for example on NuGet http://blogs.msdn.com/b/astoriateam/archive/2012/05/18/wcf-data-services-5-0-1-released.aspx).
Once you have that you might need to force the server to use V3 in the response payload since by default it will use the lowest possible version for the response. This can be done by sending a MinDataServiceVersion: 3.0; header with the request from the client.
After this even JSON Verbose payloads should use the ISO date time format.
I believe that you should be able to feed the string value sent back into the datetime.parse(http://msdn.microsoft.com/en-us/library/1k1skd40.aspx) and shouldn't have to worry about the rest
Here is an example usage: http://www.dotnetperls.com/datetime-parse

Resources