DataContractJsonSerializer DateTime implicit timezone conversion - c#

I have a date time in the database and I retrieve it from the database using Entity Framework, I then pass out the data via JSON API through the DataContractJsonSerializer.
The time in the date time field appears to have been adjusted according to the local timezone of the server whilst being processed in DataContractJsonSerializer. The epoch expressed time is 1 hour ahead of the time expected. The DateTime Kind is UTC, but previously it was Unspecified and I had the same issue.
In my application, I wish to convert between timezones explicitly and on the client side, not the server, as this makes more sense. I'm surprised at this implicit functionality as my datetime values should be simple values just like an integer.
thanks

DataContractJsonSerializer will output the timezone portion (+zzzz) if your DateTime.Kind is equal to Local OR Unspecified. This behaviour differs from the XmlSerializer which only outputs the timezone portion if Kind equals Unspecified.
If curious check out the source for JsonWriterDelegator which contains the following method:
internal override void WriteDateTime(DateTime value)
{
// ToUniversalTime() truncates dates to DateTime.MaxValue or DateTime.MinValue instead of throwing
// This will break round-tripping of these dates (see bug 9690 in CSD Developer Framework)
if (value.Kind != DateTimeKind.Utc)
{
long tickCount = value.Ticks - TimeZone.CurrentTimeZone.GetUtcOffset(value).Ticks;
if ((tickCount > DateTime.MaxValue.Ticks) || (tickCount < DateTime.MinValue.Ticks))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.JsonDateTimeOutOfRange), new ArgumentOutOfRangeException("value")));
}
}
writer.WriteString(JsonGlobals.DateTimeStartGuardReader);
writer.WriteValue((value.ToUniversalTime().Ticks - JsonGlobals.unixEpochTicks) / 10000);
switch (value.Kind)
{
case DateTimeKind.Unspecified:
case DateTimeKind.Local:
// +"zzzz";
TimeSpan ts = TimeZone.CurrentTimeZone.GetUtcOffset(value.ToLocalTime());
if (ts.Ticks < 0)
{
writer.WriteString("-");
}
else
{
writer.WriteString("+");
}
int hours = Math.Abs(ts.Hours);
writer.WriteString((hours < 10) ? "0" + hours : hours.ToString(CultureInfo.InvariantCulture));
int minutes = Math.Abs(ts.Minutes);
writer.WriteString((minutes < 10) ? "0" + minutes : minutes.ToString(CultureInfo.InvariantCulture));
break;
case DateTimeKind.Utc:
break;
}
writer.WriteString(JsonGlobals.DateTimeEndGuardReader);
}
I've run the following test on my machine
var jsonSerializer = new DataContractJsonSerializer(typeof(DateTime));
var date = DateTime.UtcNow;
Console.WriteLine("original date = " + date.ToString("s"));
using (var stream = new MemoryStream())
{
jsonSerializer.WriteObject(stream, date);
stream.Position = 0;
var deserializedDate = (DateTime)jsonSerializer.ReadObject(stream);
Console.WriteLine("deserialized date = " + deserializedDate.ToString("s"));
}
which produces the expected output:
original date = 2011-04-19T10:24:39
deserialized date = 2011-04-19T10:24:39
Thus at some point your Date must be Unspecified or Local.
After pulling it out of the DB convert the kind from Unspecified to Utc by calling
entity.Date = DateTime.SpecifyKind(entity.Date, DateTimeKind.Utc);
and don't forget to assign the return value of SpecifyKind back into your object like I have

Related

Issue around utc date - TimeZoneInfo.ConvertTimeToUtc results in date change

Having an issue whereby the date I wish to save is changing from the onscreen selected date if the users selects a timezone that is ahead x number of hours.
E.g. they choose UTC+2 Athens and date of 25/02/2016 from the calendar pop-up, then date recorded will be 24/02/2016.
I've narrowed the reasoning down to the fact that the selected datetime is recorded as for example 25/02/2016 00:00:00 and with the 2 hour offset, this takes it to 24/02/2016 22:00:00
Having never worked with timezones before, or UTC dates/times, this is highly confusing.
Here is the code -
oObject.RefDate = itTimeAndDate.ParseDateAndTimeNoUTCMap(Request, TextBox_RefDate.Text);
if (!string.IsNullOrEmpty(oObject.TimeZoneDetails))
{
TimeZoneInfo oTimeZone = TimeZoneInfo.FindSystemTimeZoneById(oObject.TimeZoneDetails);
oObject.RefDate = itTimeAndDate.GetUTCUsingTimeZone(oTimeZone, oObject.RefDate);
}
RefDate would equate to something like 25/02/2016 00:00:00 once returned from ParseDateAndTimeNoUTCMap * (code below)*
static public itDateTime ParseDateAndTimeNoUTCMap(HttpRequest oTheRequest, string sValue)
{
DateTime? oResult = ParseDateAndTimeNoUTCMapNull(oTheRequest, sValue);
if (oResult != null)
return new itDateTime(oResult.Value);
return null;
}
/// <summary>
/// Translate a string that has been entered by a user to a UTC date / time - mapping using the
/// current time zone
/// </summary>
/// <param name="oTheRequest">Request context</param>
/// <param name="sValue">Date / time string entered by a user</param>
/// <returns>UTC date / time object</returns>
static public DateTime? ParseDateAndTimeNoUTCMapNull(HttpRequest oTheRequest, string sValue)
{
try
{
if (string.IsNullOrEmpty(sValue))
return null;
sValue = sValue.Trim();
if (string.IsNullOrEmpty(sValue))
return null;
if (oTheRequest != null)
{
const DateTimeStyles iStyles = DateTimeStyles.AllowInnerWhite | DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite;
// Create array of CultureInfo objects
CultureInfo[] aCultures = new CultureInfo[oTheRequest.UserLanguages.Length + 1];
for (int iCount = oTheRequest.UserLanguages.GetLowerBound(0); iCount <= oTheRequest.UserLanguages.GetUpperBound(0);
iCount++)
{
string sLocale = oTheRequest.UserLanguages[iCount];
if (!string.IsNullOrEmpty(sLocale))
{
// Remove quality specifier, if present.
if (sLocale.Contains(";"))
sLocale = sLocale.Substring(0, sLocale.IndexOf(';'));
try
{
aCultures[iCount] = new CultureInfo(sLocale, false);
}
catch (Exception) { }
}
else
{
aCultures[iCount] = CultureInfo.CurrentCulture;
}
}
aCultures[oTheRequest.UserLanguages.Length] = CultureInfo.InvariantCulture;
// Parse input using each culture.
foreach (CultureInfo culture in aCultures)
{
DateTime oInputDate;
if (DateTime.TryParse(sValue, culture.DateTimeFormat, iStyles, out oInputDate))
return oInputDate;
}
}
return DateTime.Parse(sValue);
}
catch (Exception)
{
}
return null;
}
Once returned from the above, the following lines are executed -
TimeZoneInfo oTimeZone = TimeZoneInfo.FindSystemTimeZoneById(oObject.TimeZoneDetails);
oObject.RefDate = itTimeAndDate.GetUTCUsingTimeZone(oTimeZone, oObject.RefDate);
It is within GetUTCUsingTimeZone that the problem seems to occur to me.
static public itDateTime GetUTCUsingTimeZone(TimeZoneInfo oTimeZone, itDateTime oDateTime)
{
if (oDateTime == null || oTimeZone == null)
return oDateTime;
DateTime oLocal = DateTime.SpecifyKind(oDateTime.Value, DateTimeKind.Unspecified);
DateTime oResult = TimeZoneInfo.ConvertTimeToUtc(oLocal, oTimeZone);
return new itDateTime(oResult);
}
I have checked TimezoneInfo for the offset value, and oResult always equates to the oLocal param - the offset. So 25/02/2016 00:00:00 with a 3 hour offset would equate to 24/02/2016 21:00:00
When the offset is -hours, it goes in the other direct, so oResult = oLocal + the offset, if that makes sense. So the main issue of the date changing is not occurring in those instances.
Obviously this is not what I want. I want the date to be what the user has selected, for their timezone.
Has anyone seen something like this before? Any possible solution?
I'm not entirely sure what I've done wrong.
If you need to maintain the correct timezone, you should be using the DateTimeOffset type instead of DateTime type.
DateTimeOffset maintains the offset from UTC so you never lose your timezone information and has a lot of useful methods like
UtcDateTime
From the horses mouth:
https://msdn.microsoft.com/en-us/library/system.datetimeoffset(v=vs.110).aspx
https://learn.microsoft.com/en-us/dotnet/standard/datetime/choosing-between-datetime
The fix was to run the following after grabbing the value from the db and before redisplaying it -
static public itDateTime FixUTCUsingTimeZone(TimeZoneInfo oTimeZone, itDateTime oDateTime)
{
if (oDateTime == null || oTimeZone == null)
return oDateTime;
DateTime oTime = DateTime.SpecifyKind(oDateTime.Value, DateTimeKind.Unspecified);
DateTime oResult = TimeZoneInfo.ConvertTimeFromUtc(oTime, oTimeZone);
return new itDateTime(oResult);
}
So essentially just doing the reverse of the ConvertTimeToUtc performed earlier. Not sure why this wasn't done originally, but there you go.

Why is Convert.ToDateTime() not working in this example?

I'm trying to use both System.DateTime.Now.ToString() and Convert.ToDateTime and was running into some strange behavior. I have narrowed down the problem to the Convert.ToDateTime. For some reason a DateTime type set with System.DateTime.Now is not the same as one that has been converted from a string. However when you output either of them they appear to be the same.
(I have tried using Trim(), TrimStart(), and TrimEnd() to no avail.)
This is the output in console after running this in unity:
http://imgur.com/1ZIdPH4
using UnityEngine;
using System;
public class DateTimeTest : MonoBehaviour {
void Start () {
//Save current time as a DateTime type
DateTime saveTime = System.DateTime.Now;
//Save above DateTime as a string
string store = saveTime.ToString();
//Convert it back to a DateTime type
DateTime convertedTime = Convert.ToDateTime(store);
//Output both DateTimes
Debug.Log(saveTime + "\n" + convertedTime);
//Output whether or not they match.
if (saveTime == convertedTime)
Debug.Log("Match: Yes");
else
Debug.Log("Match: No");
//Output both DateTimes converted to binary.
Debug.Log(saveTime.ToBinary() + "\n" + (convertedTime.ToBinary()));
}
}
You lose a lot when you convert a DateTime to a string via DateTime.ToString().
Even if you include the milliseconds like this:
DateTime convertedTime =
new DateTime(
saveTime.Year,
saveTime.Month,
saveTime.Day,
saveTime.Hour,
saveTime.Minute,
saveTime.Second,
saveTime.Millisecond);
you would still get a different DateTime that is not equal to the original one.
The reason for this is that internally a DateTime stores a number of ticks (since 12:00:00 midnight, January 1, 0001). Each tick represents one ten-millionth of a second. You need to get the same number of Ticks for the two DateTime objects to be equal.
So, to get an equal DateTime, you need to do this:
DateTime convertedTime = new DateTime(saveTime.Ticks);
Or if you want to convert it to a string (to store it), you can store the ticks as a string like this:
string store = saveTime.Ticks.ToString();
DateTime convertedTime = new DateTime(Convert.ToInt64(store));
The result of DateTime.ToString() does not include milliseconds. When you convert it back to DateTime, you basically truncate the milliseconds, so it returns a different value.
For example
var dateWithMilliseconds = new DateTime(2016, 1, 4, 1, 0, 0, 100);
int beforeConversion = dateWithMilliseconds.Millisecond; // 100
var dateAsString = dateWithMilliseconds.ToString(); // 04-01-16 1:00:00 AM (or similar, depends on culture)
var dateFromString = Convert.ToDateTime(dateAsString);
int afterConversion = dateFromString.Millisecond; // 0
I think you are losing your time zone during the ToString() method. So the re-converted DateTime ends up in a different time zone.
Check also the DateTime.Kind property.

Using TimeZoneInfo to adjust a timezone's daylight-savings offset

Below is the method I use that takes in three inputs:
dateTimeInput which is a string that represents a date.
inputFormat are my format strings like this format: yyyy-MM-dd'T'HH:mm:sszzz.
timeZoneStandardName are unique timezone identifiers retrieved from var TimeZoneList = TimeZoneInfo.GetSystemTimeZones(); where the ID is retrieved via timeZoneList.Id.
I mainly used TimeZoneInfo to get my hours and minute offsets because it's very explicit as to what city/timezone it is, e.g. UTC is the input string.
public int dateTimeToUnixTime(string dateTimeInput, string inputFormat, string timeZoneStandardName)
{
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
TimeZoneInfo objTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneStandardName);
int timeZoneHours = objTimeZoneInfo.BaseUtcOffset.Hours;
int timeZoneMinutes = objTimeZoneInfo.BaseUtcOffset.Minutes;
// if input format is "yyyy-MM-dd'T'HH:mm:sszzz"
if (inputFormat == "yyyy-MM-dd'T'HH:mm:sszzz")
{
result = DateTime.ParseExact(dateTimeInput, inputFormat, provider, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
int unixTime = (Int32)(result.Subtract(Epoch)).TotalSeconds;
return unixTime;
}
else
{
// if other input formats
result = DateTime.ParseExact(dateTimeInput, inputFormat, provider, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
int unixTime = (Int32)(result.AddHours(-timeZoneHours).AddMinutes(-timeZoneMinutes).Subtract(Epoch)).TotalSeconds;
return unixTime;
}
}
My second method takes in a Unix timestamp and a timezone specifier and outputs as a location-dependent time:
public string unixTimeToDateTime(int unixInput, string outputFormat, string timeZoneStandardName)
{
// output format is "yyyy-MM-dd'T'HH:mm:sszzz"
TimeZoneInfo objTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneStandardName);
int timeZoneHours = objTimeZoneInfo.BaseUtcOffset.Hours;
int timeZoneMinutes = objTimeZoneInfo.BaseUtcOffset.Minutes;
if (outputFormat == "yyyy-MM-dd'T'HH:mm:sszzz")
{
System.DateTime dateTime = Epoch.AddSeconds(unixInput);
return dateTime.AddHours(timeZoneHours).AddMinutes(timeZoneMinutes).ToString("yyyy-MM-dd'T'HH:mm:ss") + toTimeSpan(timeZoneHours, timeZoneMinutes);
}
// output format is not
else
{
System.DateTime dateTime = Epoch.AddSeconds(unixInput).AddHours(timeZoneHours).AddMinutes(timeZoneMinutes);
return dateTime.ToString(outputFormat);
}
}
For example, here is this method in a Grasshopper component for me to show you what I mean. dateTimeToUnixTime() is my first "clock", while unixTimeToDateTime() is my second "clock"
Given an input of those list of times and a timezone marker of EST, and given those dates (mind you November 2nd 2014 1-2 AM is when we get our DST adjustments again), this method theoretically should adjust its timezone to offset an hour.
I know that TimeZoneInfo supports DST because I can use the below method to show a bool of a respective timezone's DST status.
var TimeZoneList = TimeZoneInfo.GetSystemTimeZones();
for (int i = 0; i < TimeZoneList.Count; i++)
{
Console.WriteLine(TimeZoneList[i].Id + ": " + TimeZoneList[i].SupportsDaylightSavingTime);
}
My question is, what is missing in my dateTimeToUnixTime() method that would allow automatic adjustment and offset depending on the DST conditions?
Assuming that your epoch starts at 1/1/1970, then we can use a DateTimeOffset _1970 as your epoch, add the required seconds to _1970 and then use TimeZoneInfo.ConvertTime to get a date time in the specified time zone with daylight savings adjustments (if applicable). It is important to use a DateTimeOffset and not DateTime so that the correct offset will be kept when getting the string.
private static readonly DateTimeOffset _1970 = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
public string UnixTimeToDateTime(int unixInput, string outputFormat, string timeZoneStandardName)
{
var objTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneStandardName);
var utcDate = _1970.AddSeconds(unixInput);
DateTimeOffset localDate = TimeZoneInfo.ConvertTime(utcDate, objTimeZoneInfo);
return localDate.ToString(outputFormat);
}
//1970-01-01T13:00:00+13:00
Console.WriteLine( UnixTimeToDateTime(0, "yyyy-MM-dd'T'HH:mm:sszzz", "New Zealand Standard Time"));
//1970-01-01T08:00:00+08:00
Console.WriteLine(UnixTimeToDateTime(0, "yyyy-MM-dd'T'HH:mm:sszzz", "Singapore Standard Time"));
//1969-12-31T19:00:00-05:00
Console.WriteLine(UnixTimeToDateTime(0, "yyyy-MM-dd'T'HH:mm:sszzz", "Eastern Standard Time"));
It is important to note that using TimeZoneInfo may not have accurate information about historical date adjustments, so if that is important to you, then you may be better using a library such as Node Time.

check if date time string contains time

I have run into an issue. I'm obtaining a date time string from the database and and some of these date time strings does not contain time. But as for the new requirement every date time string should contain the time like so,
1)1980/10/11 12:00:01
2)2010/APRIL/02 17:10:00
3)10/02/10 03:30:34
Date can be in any format followed by the time in 24hr notation.
I tried to detect the existence of time via the following code,
string timestamp_string = "2013/04/08 17:30";
DateTime timestamp = Convert.ToDateTime(timestamp_string);
string time ="";
if (timestamp_string.Length > 10)
{
time = timestamp.ToString("hh:mm");
}
else {
time = "Time not registered";
}
MessageBox.Show(time);
But this only works for the No 1) type timestamps. May I please know how to achieve this task on how to detect if the time element exist in this date time string. Thank you very much :)
POSSIBLE MATCH
How to validate if a "date and time" string only has a time?
INFO the three answers provided by Arun Selva Kumar,Guru Kara,Patipol Paripoonnanonda are all correct and checks for the time and serves my purpose. But I select Guru Karas answer solely on ease of use and for the explanation he has given. Thank you very much :) very much appreciated all of you :)
The date time components TimeOfDay is what you need.
MSDN says "Unlike the Date property, which returns a DateTime value that represents a date without its time component, the TimeOfDay property returns a TimeSpan value that represents a DateTime value's time component."
Here is an example with consideration of all your scenarios.
Since you are sure of the format you can use DateTime.Parse else please use DateTime.TryParse
var dateTime1 = System.DateTime.Parse("1980/10/11 12:00:00");
var dateTime2 = System.DateTime.Parse("2010/APRIL/02 17:10:00");
var dateTime3 = System.DateTime.Parse("10/02/10 03:30:34");
var dateTime4 = System.DateTime.Parse("02/20/10");
if (dateTime1.TimeOfDay.TotalSeconds == 0) {
Console.WriteLine("1980/10/11 12:00:00 - does not have Time");
} else {
Console.WriteLine("1980/10/11 12:00:00 - has Time");
}
if (dateTime2.TimeOfDay.TotalSeconds == 0) {
Console.WriteLine("2010/APRIL/02 17:10:00 - does not have Time");
} else {
Console.WriteLine("2010/APRIL/02 17:10:00 - Has Time");
}
if (dateTime3.TimeOfDay.TotalSeconds == 0) {
Console.WriteLine("10/02/10 03:30:34 - does not have Time");
} else {
Console.WriteLine("10/02/10 03:30:34 - Has Time");
}
if (dateTime4.TimeOfDay.TotalSeconds == 0) {
Console.WriteLine("02/20/10 - does not have Time");
} else {
Console.WriteLine("02/20/10 - Has Time");
}
Try this,
DateTime myDate;
if (DateTime.TryParseExact(inputString, "dd-MM-yyyy hh:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate))
{
//String has Date and Time
}
else
{
//String has only Date Portion
}
You can try using other format specifiers as listed here, http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Combining the answers of Guru Kara and Patipol Paripoonnanonda with the .net globalisation API results in:
bool HasExplicitTime(DateTime parsedTimestamp, string str_timestamp)
{
string[] dateTimeSeparators = { "T", " ", "#" };
string[] timeSeparators = {
CultureInfo.CurrentUICulture.DateTimeFormat.TimeSeparator,
CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator,
":"};
if (parsedTimestamp.TimeOfDay.TotalSeconds != 0)
return true;
string[] dateOrTimeParts = str_timestamp.Split(
dateTimeSeparators,
StringSplitOptions.RemoveEmptyEntries);
bool hasTimePart = dateOrTimeParts.Any(part =>
part.Split(
timeSeparators,
StringSplitOptions.RemoveEmptyEntries).Length > 1);
return hasTimePart;
}
This approach:
detects explicit midnight times (e.g. "2015-02-26T00:00");
only searches the string when TimeOfDay indicates midnight or no explicit time; and
finds explicit midnight times in local format and any non midnight time in any format that .net can parse.
Limitations:
explicit midnight times in non culture local format are not detected;
explicit midnight times with less than two parts are not detected; and
less simple and elegant than the approaches of Guru Kara and Patipol Paripoonnanonda.
Here's what I'm going with for now. It may not be perfect, but likely better than considering any 12am datetime as not having a time. The premise is that if I tack a full time specification on the end it will parse if it's just a date but fail if it already has a time component.
I had to make the assumption that there's not some valid, date/time that has 7 non-white-space characters or less. It appears that "1980/10" parses, but not "1980/10 01:01:01.001".
I've included various test cases. Feel free to add your own and let me know if they fail.
public static bool IsValidDateTime(this string dateString, bool requireTime = false)
{
DateTime outDate;
if(!DateTime.TryParse(dateString, out outDate)) return false;
if (!requireTime) return true;
else
{
return Regex.Replace(dateString, #"\s", "").Length > 7
&& !DateTime.TryParse(dateString + " 01:01:01.001", out outDate);
}
}
public void DateTest()
{
var withTimes = new[]{
"1980/10/11 01:01:01.001",
"02/01/1980 01:01:01.001",
"1980-01-01 01:01:01.001",
"1980/10/11 00:00",
"1980/10/11 1pm",
"1980-01-01 00:00:00"};
//Make sure our ones with time pass both tests
foreach(var date in withTimes){
Assert.IsTrue(date.IsValidDateTime(), String.Format("date: {0} isn't valid.", date));
Assert.IsTrue(date.IsValidDateTime(true), String.Format("date: {0} does have time.", date));
}
var withoutTimes = new[]{
"1980/10/11",
"1980/10",
"1980/10 ",
"10/1980",
"1980 01",
"1980/10/11 ",
"02/01/1980",
"1980-01-01"};
//Make sure our ones without time pass the first and fail the second
foreach (var date in withoutTimes)
{
Assert.IsTrue(date.IsValidDateTime(), String.Format("date: {0} isn't valid.", date));
Assert.IsFalse(date.IsValidDateTime(true), String.Format("date: {0} doesn't have time.", date) );
}
var bogusTimes = new[]{
"1980",
"1980 01:01",
"80 01:01",
"1980T01",
"80T01:01",
"1980-01-01T01",
};
//Make sure our ones without time pass the first and fail the second
foreach (var date in bogusTimes)
{
DateTime parsedDate;
DateTime.TryParse(date, out parsedDate);
Assert.IsFalse(date.IsValidDateTime(), String.Format("date: {0} is valid. {1}", date, parsedDate));
Assert.IsFalse(date.IsValidDateTime(true), String.Format("date: {0} is valid. {1}", date, parsedDate));
}
}
Would this work for your use case:
bool noTime = _datetimevalue.TimeOfDay.Ticks == 0;
If no time component exists in the DateTime instance, Ticks will be 0.
Date and time are always separated by a space bar. The easiest way would be:
if (timestamp_string.Split(' ').Length == 2)
{
// timestamp_string has both date and time
}
else
{
// timestamp_string only has the date
}
This code assumes the date always exists.
If you want take it further (in case the date does not exist), you can do:
if (timestamp_string.Split(' ')
.Select(item => item.Split(':').Length > 1)
.Any(item => item))
{
// this would work for any string format that contains date, for example:
// 2012/APRIL/03 12:00:05 -> this would work
// 2013/04/05 09:00:01 -> this would work
// 08:50:45 2013/01/01 -> this would also work
// 08:50:50 -> this would also work
}
else
{
// no date in the timestamp_string at all
}
Hope this helps!

Parsing user input including tz database time zone name

I'm attempting to parse user input with Noda Time.
Input:
Date in the form of YYYY-MM-DD
Hour
Minute
tz database time zone name (returned from Google's Time Zone API)
I need to convert this data to UTC and to other time zones, also based on a tz database time zone name.
Currently I'm trying to make sense of the LocalDateTime and ZonedDateTime differences, but perhaps someone is able to show how to do this before I'd (hopefully) figure this out.
Your answer is pretty close to what I'd do - but if you have the date, hour and minute in separate strings, I'd use:
var zoneProvider = DateTimeZoneProviders.Tzdb;
var sourceZone = zoneProvider.GetZoneOrNull("Europe/Brussels");
var targetZone = zoneProvider.GetZoneOrNull("Australia/Melbourne");
if (sourceZone == null || targetZone == null)
{
Console.WriteLine("Time zone not found");
return;
}
var dateParseResult = LocalDatePattern.IsoPattern.Parse(date);
int hourValue, minuteValue;
if (!dateParseResult.Success ||
!int.TryParse(hour, out hourValue) ||
!int.TryParse(minute, out minuteValue))
{
Console.WriteLine("Parsing failed");
return;
}
var localDateTime = dateParseResult.Value + new LocalTime(hour, minute);
var zonedDateTime = localDateTime.InZoneStrictly(sourceZone);
Console.WriteLine(zonedDateTime.ToInstant());
Console.WriteLine(zonedDateTime);
Console.WriteLine(zonedDateTime.WithZone(targetZone));
The only significant difference here is the parsing - I wouldn't stick all the bits together; I'd just parse the strings separately. (I also prefer "early outs" for failures :)
You should note the meaning of InZoneStrictly though - do you definitely want to fail if the input local date/time is ambiguous?
http://msmvps.com/blogs/jon_skeet/archive/2012/02.aspx has great information, and while it's slightly outdated it's easy to find the relevant method names in the official documentation.
Below is some demonstration code.
string date = "2013-01-22";
string hour = "13";
string minute = "15";
var result = LocalDateTimePattern.ExtendedIsoPattern.Parse(date + "T" + hour + ":" + minute + ":00");
if (result.Success == true)
{
DateTimeZone source_zone = DateTimeZoneProviders.Tzdb.GetZoneOrNull("Europe/Brussels");
DateTimeZone target_zone = DateTimeZoneProviders.Tzdb.GetZoneOrNull("Australia/Melbourne");
if (source_zone != null && target_zone != null)
{
ZonedDateTime source_zoned_dt = result.Value.InZoneStrictly(source_zone);
Console.WriteLine(source_zoned_dt.ToInstant());
Console.WriteLine(source_zoned_dt);
Console.WriteLine(source_zoned_dt.WithZone(target_zone));
}
else
{
Console.WriteLine("time zone not found");
}
}
else
{
Console.WriteLine("parsing failed");
}

Categories