-1

I'm writing an automation date and I want to extract a string, turn it into a DateTime object, and compare it with the current date and time.

The string in question has this format: 7/28/2017 1:17:29 PM

How can I convert it to a DateTime object to compare with the current time (Basically, my end goal is to verify that it is within a few minutes of the current time)

Andrio
  • 1,852
  • 2
  • 25
  • 54

2 Answers2

2

System.Convert can convert to and from many types. For example...

int intElapsedMinutes = (DateTime.Now - Convert.ToDateTime("7/28/2017 1:17:29 PM")).TotalMinutes
J. Cox
  • 21
  • 3
1

Use DateTime.Parse() or DateTime.TryParse()

Rahul
  • 76,197
  • 13
  • 71
  • 125
SledgeHammer
  • 7,338
  • 6
  • 41
  • 86
  • `DateTime.Parse()` worked, thank you. I knew the Method existed, but I didn't think it'd be smart enough to convert the string without some help – Andrio Jul 28 '17 at 19:51
  • Sometimes it's not. If the format is constant, use `ParseExact`, or you have a bug waiting to happen. – D Stanley Jul 28 '17 at 19:53