解析24小时以上时间在C# [英] Parsing times above 24 hours in C#

查看:183
本文介绍了解析24小时以上时间在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个时间戳(只是时间或日期和时间),其中时间可以翻转到第二天:




00: 〇点00< - 午夜



1时00分00秒< - 上午01点



23点00分:00< - 下午11点



&24:00:00 LT; - 午夜,天+ 1



25:00:00< - 凌晨1点,天+ 1




会是怎样一种方式来轻松地分析它变成一个C#的DateTime这将执行结转到下一天?换句话说,01:00:00将成为0001-01-01 01:00:00和25:00:00将成为0001-01-02 01:00:00。



编辑:



我要指出,这悲惨的失败(即FormatException):

  DateTime.ParseExact(0001-01-01 25:00:00,YYYY-MM-DD HH:MM:SS,CultureInfo.InvariantCulture) ; 


解决方案

既然你想表现一段时间从任意角度,而不是作为一个特定日期,也许你会过得更好使用系统。时间跨度类?这允许您设置超过24小时值在构造函数中,并能与datetime对象这样使用:

 系统.TimeSpan时间戳=新System.TimeSpan(25,0,0); 
的System.DateTime parsedDateTime =新日期时间(0,0,0);
parsedDateTime = parsedDateTime.Add(时间戳);
Console.WriteLine(parsedDateTime.ToString(YYYY-MM-DD HH:MM:SS)); //输出为0001-01-02 1时00分零零秒

注意: 代码是未经测试



编辑:在解析字符串而言,我想不出任何基本的.NET对象用(因为25是一天一个无效小时),但假设格式是一致的小时值大于23的解析字符串,你可以创建一个非常简单的字符串解析程序(甚至是正则表达式)来读取值分别和手动加载构造。


Suppose a time stamp (just time or date and time) where the time can roll over to the next day:

00:00:00 <- midnight

01:00:00 <- 1 AM

23:00:00 <- 11 PM

24:00:00 <- midnight, day + 1

25:00:00 <- 1 AM, day + 1

What would be a way to parse it easily into a C# DateTime that would perform the carry-over to the next day? In other words, "01:00:00" would become "0001-01-01 01:00:00" and "25:00:00" would become "0001-01-02 01:00:00".

EDIT:

I should mention that this fails miserably (i.e FormatException):

DateTime.ParseExact("0001-01-01 25:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

解决方案

Since you're trying to represent a period of time from an arbitrary point, rather than as a specific date, perhaps you would be better off using the System.TimeSpan class? This allows you to set values of more than 24 hours in the constructor, and can be used with DateTime objects like this:

System.TimeSpan timestamp = new System.TimeSpan(25, 0, 0);
System.DateTime parsedDateTime = new DateTime(0, 0, 0);
parsedDateTime = parsedDateTime.Add(timestamp);
Console.WriteLine(parsedDateTime.ToString("yyyy-MM-dd HH:mm:ss"));  //Output as "0001-01-02 01:00:00"

NOTE: Code is untested.

EDIT: In terms of parsing the strings, I can't think of any basic .NET objects that parse strings with values greater than 23 for the hour (since 25 is an invalid hour of the day), but assuming that the format is consistent, you could create a very simple string parsing routine (or even a regular expression) to read the values individually, and load the constructor manually.

这篇关于解析24小时以上时间在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆