简体   繁体   English

如何获得给定日期和时间的 TimeSpan

[英]How do I get TimeSpan given a date and a time

Is it possible to get the timespan of A and B, where A(MM-dd-yyyy) = 10-06-2015 23:45 and B = 9:00 AM .是否有可能获得 A 和 B 的时间跨度,其中 A(MM-dd-yyyy) = 10-06-2015 23:45和 B = 9:00 AM The given format of data are exactly what it is on this post.给定的数据格式正是这篇文章中的内容。 I guess am having trouble on formatting, no coded work yet.我想在格式化方面有问题,还没有编码工作。

I have other question that may linked to the first, is if(A>B) possible ?我还有其他问题可能与第一个有关, if(A>B)可能? where A(MM-dd-yyyy) = 10-06-2015 23:45 and B = 9:00 AM .其中 A(MM-dd-yyyy) = 10-06-2015 23:45和 B = 9:00 AM Does comparing the two data possible ?是否可以比较这两个数据?

DateTime a = DateTime.ParseExact( "10-06-2015 23:45"  , "MM-dd-yyyy HH:mm"   , CultureInfo.InvariantCulture );
DateTime b = DateTime.ParseExact( "10-06-2015 9:00 AM", "MM-dd-yyyy hh:mm tt", CultureInfo.InvariantCulture );
TimeSpan difference = a - b;

If you only know b by the time-of-day, then this works:如果你只知道b的时间,那么这有效:

DateTime b = DateTime.ParseExact( "9:00 AM" "hh:mm tt", CultureInfo.InvariantCulture );
b = a.Date.Add( b.TimeOfDay );

TimeSpan difference = a - b;

You say you're using DateTimePicker , in which case:你说你正在使用DateTimePicker ,在这种情况下:

DateTime a = dateTimePicker1.Value;
DateTime b = a.Date.Add( dateTimePicker2.TimeOfDay );
TimeSpan difference = a - b;

Use TimeOfDay for this.为此使用TimeOfDay

This will also help. 也会有所帮助。

Example: Define your times like this.示例:像这样定义你的时间。

startDate='10-06-2015' startTime=10-06-2015 23:45:00 AM'

TimeSpan ts = startTime.TimeOfDay;
DateTime dt = startDate.Add(ts);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM