Angular DatePipe Timezone with .NET Dates

Francisco Daniel Salazar Aguirre
2 min readDec 15, 2020

The problem comes from the JSON spec itself: there is no literal syntax for dates in JSON. The spec has objects, arrays, strings, integers, and floats, but it defines no standard for what a date looks like.

The default format used by Json.NET is the ISO 8601 standard: “2012–03–19T07:22Z”.

Prior to Json.NET 4.5 dates were written using the Microsoft format: “\/Date(1198908717056)\/”. If you want to use this format, or you want to maintain compatibility with Microsoft JSON serializers or older versions of Json.NET, then change the DateFormatHandling setting to MicrosoftDateFormat.

Even now we are using this weird format on rest services on .NET so is good to know how to handle them.

In the case of Angular, you require a Pipe convertor since The JavaScriptDateTimeConverter class is one of the two DateTime JsonConverters that come with Json.NET. This converter serializes a DateTime as a JavaScript Date object: new Date(1234656000000)

Technically this is invalid JSON according to the spec, but all browsers and some JSON frameworks, including Json.NET, support it.

@Pipe({
name: ‘jsonDateFormat’,
})
export class JsonDateFormatPipe implements PipeTransform {
public transform(input: string): Date {
if (!input || !_.isString(input)) {
return null;
}
return new Date(parseInt(input.substr(6), 10));
}
}

From angular 5 and up, you can add timezone in the normal pipe (Date), that is not coming from JSON .NET services.

date_expression | date[:format[:timezone[:locale]]]

You can get the client’s offset in minutes and make conditions for the date using (new Date()).getTimezoneOffset() however this is filthy, and you could know that the date is on EST or CST so you don't need to add more modification to set it on the timezone you want, you only need to have the date format and add the timezone on the format:

{{ Date | jsonDateFormat | date: 'mediumDate': 'EST' }}

With the example above you are using .NET Dates converting to Date and saying in which timezone is the origin of the date so if the captured timezone is on EST but you are on PST or any timezone is going to make the conversion of the date to the client timezone showing the correct hour.

Code: https://github.com/angular/angular/blob/5.0.4/packages/common/src/pipes/date_pipe.ts#L137

Docs:

https://angular.io/api/common/DatePipe

--

--

Francisco Daniel Salazar Aguirre

Full stack developer , that can be named jack of all trades master of none but oftentimes better than a master of one. Still looking for improving all trades.