您应该考虑要求时区。1不需要它,但是#2和#3需要它。
public DateTime ParseRequestDate(){ // https://stackoverflow.com/questions/2883576/how-do-you-convert-epoch-time-in-c CultureInfo enUS = new CultureInfo("en-US"); var dt = "1374755180"; //var dt = "7/25/2013 6:37:31 PM"; //var dt = "2013-07-25 14:26:00"; DateTime datevalue; long dtLong; // Scenario #1 if (long.TryParse(dt, out dtLong)) return dtLong.FromUnixTime(); // Scenario #2 if (DateTime.TryParseExact(dt, "MM/dd/yyyy hh:mm:ss tt", enUS, DateTimeStyles.None, out datevalue)) return datevalue; // Scenario #3 if (DateTime.TryParseExact(dt, "yyyy-MM-dd hh:mm:ss", enUS, DateTimeStyles.None, out datevalue)) return datevalue; throw new SomeException("Don't know how to parse...");}
编辑 正如Matt Johnson指出的那样,DateTime.TryParseExact接受一个格式字符串数组。2&3可能会凝聚。
public DateTime ParseRequestDate(){ // https://stackoverflow.com/questions/2883576/how-do-you-convert-epoch-time-in-c CultureInfo enUS = new CultureInfo("en-US"); var dt = "1374755180"; //var dt = "7/25/2013 6:37:31 PM"; //var dt = "2013-07-25 14:26:00"; DateTime datevalue; long dtLong; // Scenario #1 if (long.TryParse(dt, out dtLong)) return dtLong.FromUnixTime(); // Scenario #2 & #3 var formatStrings = new string[] { "MM/dd/yyyy hh:mm:ss tt", "yyyy-MM-dd hh:mm:ss" }; if (DateTime.TryParseExact(dt, formatStrings, enUS, DateTimeStyles.None, out datevalue)) return datevalue; throw new SomeException("Don't know how to parse...");}
我从另一个问题借来的时代转换。 (扩展方法)
public static class MyExtensions{ public static DateTime FromUnixTime(this long unixTime) { var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return epoch.AddSeconds(unixTime); }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)