VB.NET compare date time from string format

2019-09-22 13:41发布

I have this string: 28 June 2018 (22:05)

How can I compare it with my current time and get the difference?

For example if actual time was 29/06/2018 (05:49)

The difference will be: 7 hours 44 minutes

So input: 28 June 2018 (22:05) Output: 7 hours 44 minutes

标签: vb.net
1条回答
Lonely孤独者°
2楼-- · 2019-09-22 14:01

The first thing you need to do, is convert the string to a valid DateTime instance.

If you know your dates will always be in this format, you can do the following...

Dim mydate = DateTime.ParseExact("28 June 2018 (22:05)", "dd MMMM yyyy (HH:mm)", CultureInfo.InvariantCulture)

https://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx

Once you've parsed the string into a valid DateTime instance, you can use all the normal date functions to do the comparisons.

I would first get the difference in minutes, like so...

Dim diffminutes = DateDiff(DateInterval.Minute, mydate, Now)

Then create a timespan like this...

Dim mytimespan = TimeSpan.FromMinutes(diffminutes)

Finally display the difference in hours and minutes like this...

Response.Write(mytimespan.ToString("hh\:mm"))
查看更多
登录 后发表回答