ACristian24
ACristian24

Reputation: 385

DateTime value from backend to frontend

I've been struggling for days with some DateTime values.

I have an API backend that uses entity framework and sql server with .netcore.

The big issue when i want to send a datetime from angular to c# backend. I noticed that Date() in typescript/javascript by default uses my timezone and i don't know how to exclude it.

For example my date looks like this: Wed Jul 11 2019 21:00:00 GMT+0300 And when it arrived in c# it becomes 07/10/2010(mm-dd-yyyy), it subtracts 1 day due to timezone.

Is there a way to standardize the Date variable to ignore timezone and always keep the same format DD-MM-YYYY ?

I've also tried to use MomentJS and still can't figure it out, even my MomentJS compares are acting strange due tot his issue.

For example:

const VacationStart = moment(calendarEntity.Vacation.StartTime).utc(false);
const VacationEnd = moment(calendarEntity.Vacation.EndTime).utc(false);
if (VacationStart.isSameOrBefore(ColumnDate,'day') && VacationEnd.isSameOrAfter(ColumnDate,'day')) {
            return '#FF0000';
 }

In the above example:

VacationStart is Wed Jul 10 2019 21:00:00 GMT+0300

VacationEnd is Wed Jul 17 2019 00:00:00 GMT+0300

ColumnDate is Thu Aug 15 2019 03:00:00 GMT+0300 (incremental value)

Yet for some reason even if i use isSameOrBefore(ColumnDate,'day') to specify to compare only up to days it still does not work. When VacationEnd should be equal to ColumnDate is return false.

Note: everything is in a foreach loop where ColumnDate increases by +1 day.

Upvotes: 0

Views: 3851

Answers (1)

Paul Story
Paul Story

Reputation: 592

You just need to use UTC time (Greenwich Mean Time)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC https://learn.microsoft.com/en-us/dotnet/api/system.datetime.utcnow?view=netcore-2.2

So something like this:

  • new Date(new Date().toUTCString()); -- "Mon Jul 01 2019 17:55:41 GMT-0700 (Pacific Daylight Time)"
  • new Date().toUTCString(); -- "Tue, 02 Jul 2019 00:56:38 GMT"
  • new Date().toString(); -- "Mon Jul 01 2019 17:57:03 GMT-0700 (Pacific Daylight Time)"

Upvotes: 1

Related Questions