In this previous post, I showed how to get Australian timezone name by state using Noda Time from UTC. In one of my recent tasks, I need to get the current date at 5pm local time to the user from an UTC date time in the format “yyyy-MM-ddTHH:mm:ss.fffK”. The user timezone is important here. The last K on string will be changed to ‘Z’ if the date is UTC or with timezone (+-hh:mm) if is local.
In the previous post, we have this ConvertUtcToZonedDateTime method which converts a UTC DateTime to Noda Time ZonedDateTime based on an Australian state.
public static ZonedDateTime ConvertUtcToZonedDateTime(this DateTime dateTime, string state)
{
if (!dateTimeZones.ContainsKey(state))
{
throw new NotSupportedException($"State is not supported {state}");
}
var time = Instant.FromDateTimeUtc(dateTime.ToUniversalTime());
var zone = dateTimeZones[state];
var zonedTime = time.InZone(zone);
return zonedTime;
}
We’ll use this same method to get the local date time from UTC and then create a new LocalDateTime with time we need based on the local date.
var state = "NSW";
var currentLocalDateTime = DateTime.UtcNow.ConvertUtcToZonedDateTime(state);
var currentYear = currentLocalDateTime.Year;
var currentMonth = currentLocalDateTime.Month;
var currentDay = currentLocalDateTime.Day;
var result = currentLocalDateTime
.AtStrictly(new LocalDateTime(currentYear, currentMonth, currentDay, 17, 0, 0))
.ToDateTimeOffset()
.ToString("yyyy-MM-ddTHH:mm:ss.fffK");