1

I am having trouble correctly transporting my date and timezone to my backend. I am using a DateTimeOffset in the backend and a TypeScript date in the frontend. I attempted to convert the date to the correct format using moment.js, but unfortunately, I was unsuccessful. Can you please assist me with this issue? I am unsure whether to convert the backend DateTimeOffset to a string, as it is difficult to implement and not the optimal solution. Unfortunately, my research has not yielded any helpful results. I am using the datetime-local text field from Fluent UI, which requires me to convert the date format multiple times.

Frontend:

    //model
    export interface Setting {
            validFrom?: Date;
            validTo?: Date;
        }
    //apiService
    public async createSetting(setting: Setting): Promise<any> {
    let postUrl = ``
    try {
      return await axios.post(postUrl, setting)
    } catch (ex) {
      return ex
    }  
}


// Formating for saving
        const parseDateForSave = (dateString?: string) => {
            console.log("parseDateForSave: " +dateString);
            return dateString ? moment.tz(dateString, "Europe/Berlin").toDate() : undefined;
        };


//format for displaying in textfield
        const formatDateForDisplay = (dateTime?: Date | string) => {
            if (!dateTime) {
                return '';
            }
            const date = typeof dateTime === 'string' ? new Date(dateTime) : dateTime;
            return moment(date).format('YYYY-MM-DDTHH:mm');
        };

The console in the frontend shows it to me as expected, but I have read that it already performs formatting.

F12 console: setting from: 2023-12-11 08:49:00 +01:00 to 2023-12-17 09:49:00 +01:00

Backend:

   [HttpPost]
    [Route("")]
    public async Task<ActionResult<Setting>> CreateSetting([FromBody] Setting setting)
    {
        try
        {
            .....
        }
        catch (Exception ex)
        {
....
        }
    }

    public class Setting : xxx
{
    public DateTimeOffset? ValidFrom { get; set; }
    public DateTimeOffset? ValidTo { get; set; }
    public DateTimeOffset? LastUpdate { get; set; }}

The LastUpdate Date appears one hour too early in the backend due to the absence of the time zone. In the backend, I set the LastUpdate Date using DateTimeOffset.Now. This writes the value, including the time zone, correctly into the database.

Thanks and bye

18
  • Don't try to modify the Date values before posting. A Date has no format itself and JSON.stringify will correctly create an ISO8601 date string at UTC ie +00:00. ASP.NET can handle that correctly into a UTC DateTimeOffset. Commented Dec 14, 2023 at 7:40
  • @PanagiotisKanavos Do you mean the parseDateForSave method? I converted my dateString to a new date, but it still doesn't work. Commented Dec 14, 2023 at 7:45
  • A UTC time will always be 1 or 2 hours behind Berlin time. Are you sure you aren't misinterpreting UTC as local time? What does dateString contain? Commented Dec 14, 2023 at 7:50
  • 1
    The formats are the same. ValidFrom is a local time and doesn't have an offset though. It's probably the value of an input type='datetime-local'. You can convert it into a date directly with new Date(dateString). This will produce a local time that's correctly serialized as ISO8601 at UTC Commented Dec 14, 2023 at 8:05
  • 1
    @PuygrenierSolann - ToUniversalTime and DateTime.ToLocalTime should be avoided in server-side code, as they will use the time zone of the server, which is usually not the time zone of the user (and is often UTC, making them a no-op). Commented Dec 14, 2023 at 21:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.