Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Integer Value As Datetime

I have date represented as integer like 20140820 and I want to parsing it as datetime, like 2014.08.20.

Do I need to parse each integer value (2014)(08)(02) using index or is there simpler way?

like image 238
user1765862 Avatar asked Aug 20 '14 08:08

user1765862


People also ask

How do you convert int to datetime in Python?

Use pandas. to_datetime() to Convert Integer to Date & Time Format. Let's suppose that your integers contain both the date and time. In that case, the format should be specify is '%Y%m%d%H%M%S' .

What is datetime parse in C#?

The DateTime. ParseExact method converts the specified string representation of a datetime to a DateTime . The datetime string format must match the specified format exactly; otherwise an exception is thrown. Date & time is culture specific; the methods either use the current culture or accept a specific culture.

Which is an example of correctly parsing a date time string into a datetime object in net?

DateTime dateTime10 = DateTime. ParseExact(dateString, "mm/dd/yyyy", provider); dateString = "not a date"; // Exception: The string was not recognized as a valid DateTime.


2 Answers

If your CurrentCulture supports yyyyMMdd format as a standard date and time format, you can just use DateTime.Parse method like;

int i = 20140820; DateTime dt = DateTime.Parse(i.ToString()); 

If it doesn't support, you need to use DateTime.ParseExact or DateTime.TryParseExact methods to parse it as custom date and time format.

int i = 20140820; DateTime dt; if(DateTime.TryParseExact(i.ToString(), "yyyyMMdd",                            CultureInfo.InvariantCulture,                           DateTimeStyles.None, out dt)) {     Console.WriteLine(dt); } 

Then you can format your DateTime with .ToString() method like;

string formattedDateTime = dt.ToString("yyyy.MM.dd", CultureInfo.InvariantCulture); 
like image 65
Soner Gönül Avatar answered Sep 19 '22 23:09

Soner Gönül


The easiest and most performance way would be something like:

int date = 20140820;  int d = date % 100; int m = (date / 100) % 100; int y = date / 10000;  var result = new DateTime(y, m, d); 
like image 34
Lanorkin Avatar answered Sep 21 '22 23:09

Lanorkin