@manhng

Welcome to my blog!

Cross-platform Time Zones with .NET Core

August 30, 2021 18:23

Time Zones with .NET Core (edit)

Fully-featured .NET library for working with Cron expressions. Built with time zones in mind and intuitively handles daylight saving time transitions

HangfireIO/Cronos: Fully-featured .NET library for working with Cron expressions. Built with time zones in mind and intuitively handles daylight saving time transitions (github.com)

Schedule Cron Jobs using HostedService in ASP.NET Core | by Changhui Xu | codeburst

Cross-platform Time Zones with .NET Core | .NET Blog (microsoft.com)

Getting local-time of specific Time Zone using .Net Core micro-services in Cloud | by Vijayavel Palaniappan | Medium

.NET Tips: Get TimeZone Data on Different Platforms | by Jiadong Chen | Level Up Coding (gitconnected.com)

NuGet

<PackageReference Include="Cronos" Version="0.7.1" />

appsettings.json

"TimeZoneId": "Tokyo Standard Time"

CronJobConfig

public class CronJobConfig
{
public int Interval { get; set; }
public string ExportTime { get; set; }
public string TimeZoneId { get; set; }
public int DataRow { get; set; }
public char Delimiter { get; set; }
}

DateTimeUtil.cs

public static DateTime GetCurrentDateTimeInTimeZone(string timeZoneId)
{
return TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, GetTimeZoneInfo(timeZoneId));
}

public static TimeZoneInfo GetTimeZoneInfo(string timeZoneId)
{
if (string.IsNullOrEmpty(timeZoneId))
return TimeZoneInfo.Utc;

try
{
return TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
}
catch
{
return TimeZoneInfo.Utc;
}
}

Usage

var currentDateTime = DateTimeUtil.GetCurrentDateTimeInTimeZone(timeZoneId);

Categories

Recent posts