Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to datetime conversion using System.Globalization.CultureInfo.InvariantCulture

Tags:

c#

datetime

mysql

I have the following code to convert string into datetime..

string updateDateTime = "1398398552695";

double temp = Double.Parse(updateDateTime);
TimeSpan sp = TimeSpan.FromMilliseconds(temp);
DateTime dt = new DateTime(1970, 1, 1).Add(sp);
updateDateTime = dt.ToString("yyyy-MM-dd HH':'mm':'ss");//final date time

string tt = dt.ToString("yyyy-MM-dd HH':'mm':'ss");
DateTime output1;
DateTime.TryParseExact(tt, "yyyy-MM-dd HH':'mm':'ss", System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.None,out output1);

DateTime output2 = DateTime.ParseExact(tt, "yyyy-MM-dd HH':'mm':'ss", System.Globalization.CultureInfo.InvariantCulture);

Console.WriteLine(dt);
Console.WriteLine(tt);
Console.WriteLine(output1);
Console.WriteLine(output2);

If we see the output it will be something like this..

25/04/2014 04:02:32//dt
2014-04-25 04:02:32//tt
25/04/2014 04:02:32//output1
25/04/2014 04:02:32//output2

the problem is if we see output1 and output2 it is actually not giving result in yyyy-MM-dd format and I need value in this format and in datetime type only coz in in database(MySQL) the field is in DateTime Format. So, i want the output in 2014-04-25 04:02:32 format but it is string and I need to convert it to datetime.

Note : There are many questions related to this problem here in stackoverflow but my reputation is not enough to comment on them so I had to create this new question..

like image 343
Silver Avatar asked Nov 01 '22 00:11

Silver


1 Answers

Your datetime is appearing this way because in your Region Settings in Control Panel Date and Time format is set this way.

Please go to Control Panel and Select Region and in Formats tab Select correct value or else go to Additional Settings to customize your Date and Time format.

like image 99
sir4ju1 Avatar answered Nov 12 '22 19:11

sir4ju1