Convert time string to DateTime in C #

How can I get a DateTime based on a string

for example: if I have mytime = "14:00"

How can I get a DateTime object with the current date as the date, if the current time was no longer 14:00:01, then the date should be the next day.

+8
c # datetime
source share
4 answers

It is as simple as parsing a DateTime with the exact format.

Achievable with

 var dateStr = "14:00"; var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None); 

The DateTime.ParseExact() (msdn link) method simply lets you pass the format string you want as a parsing string to return a DateTime structure. Now the Date mark of this line will be set by default until today's date when no date is provided.

To answer the second part

How can I get a DateTime object with the current date as the date, if only the current time is already 14:00:01, then the date should be the next day.

It is also simple, since we know that DateTime.ParseExact will return to today's date (since we did not provide a date), we can compare our parsed date with DateTime.Now . If DateTime.Now larger than our syntax date, we add 1 day to our parsed date.

 var dateStr = "14:00"; var now = DateTime.Now; var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None); if (now > dateTime) dateTime = dateTime.AddDays(1); 
+8
source share

You can use DateTime.TryParse() : it converts the specified string representation of the date and time to the DateTime equivalent and returns a value indicating whether the conversion was successful.

 string inTime="14:00"; DateTime d; if(DateTime.TryParse(inTime,out d)) { Console.WriteLine("DateTime : " + d.ToString("dd-MM-yyyy HH:mm:SS")); } 

Execution example here

+2
source share

There is a datetime constructor for

 public DateTime( int year, int month, int day, int hour, int minute, int second ) 

So, let's analyze the string to find hours, minutes and seconds and pass this to this constructor with other parameters provided by Datetime.Now.Day, etc.

+1
source share

I think you want to do something like this:

 string myTime = "14:00"; var v = myTime.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); DateTime obj = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(v[0]), int.Parse(v[1]), DateTime.Now.Second); 
+1
source share

All Articles