Click here to Skip to main content
15,887,376 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
I have the following format in a file and I want to convert that into DateTime.
How can i do that?

The format is of the following:
07/29/2015 08:48:03
Posted
Updated 30-Jul-15 4:15am
v2
Comments
[no name] 30-Jul-15 10:12am    
https://msdn.microsoft.com/en-us/library/ch92fbc1(v=vs.110).aspx or variants

Couple of points in addition to the other solutions...

1. Never assume that your data input is in the correct format.
It's better to use TryParse[^] or ParseExact[^]

2. Never assume that your code is only going to be used in your own time zone / Culture. Handle other formats/cultures in some way.

For example: (needs using System.Globalization;
C#
var test = "07/29/2015 08:48:03";

//All incoming string date representations will be in US format
var culture = CultureInfo.CreateSpecificCulture("en-US");

DateTime dtResult;
if(DateTime.TryParse(test, culture,DateTimeStyles.None, out dtResult))
    Console.WriteLine(String.Format("Output date is : {0}",dtResult));
else
    Console.WriteLine(String.Format("Input string is not a date in {0}", culture.Name));

Because my PC is currently set up for United Kingdom, this runs without error and gives (Note the change to dd/mm from mm/dd)
Output date is : 29/07/2015 08:48:03
 
Share this answer
 
Comments
Richard Deeming 30-Jul-15 15:04pm    
CHill60 1-Aug-15 13:32pm    
A virtual 5!
Maybe this article here on CodeProject can help you out:
C# Date Time Parser[^]

Good luck!
 
Share this answer
 
You can convert it or parse it to DateTime if it is correct format. (This can be) Use either one of the following codes to do what you want to.

C#
var date = Convert.ToDateTime("07/29/2015 08:48:03");

// OR 

var date = DateTime.Parse("07/29/2015 08:48:03");


Both of them would work for you and they would return a DateTime object. Learn more about them on MSDN.

Convert.ToDateTime() on MSDN[^].
DateTime.Parse() on MSDN[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900