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
Datevalues before posting. ADatehas 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.dateStringcontain?ValidFromis a local time and doesn't have an offset though. It's probably the value of aninput type='datetime-local'. You can convert it into a date directly withnew Date(dateString). This will produce a local time that's correctly serialized as ISO8601 at UTCToUniversalTimeandDateTime.ToLocalTimeshould 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).