Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

VB.NET compare date time from string format

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...