Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an Object to DateTime

Tags:

c#

How to convert a string date value of such format:

Wed Oct 02 2013 00:00:00 GMT+0100 (GMT Daylight Time)

To a date of format of 02/10/2013.

I have already tried the DateTime.ParseExact but it didn't work at all:

DateTime.ParseExact(dateToConvert, "ddd MMM d yyyy HH:mm:ss GMTzzzzz",    CultureInfo.InvariantCulture);
like image 279
t_plusplus Avatar asked Oct 29 '13 15:10

t_plusplus


People also ask

How do you change an object to a datetime in Python?

The date column is indeed a string, which—remember—is denoted as an object type in Python. You can convert it to the datetime type with the . to_datetime() method in pandas .

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

How do you convert an object to a string in Python?

Python is all about objects thus the objects can be directly converted into strings using methods like str() and repr(). Str() method is used for the conversion of all built-in objects into strings. Similarly, repr() method as part of object conversion method is also used to convert an object back to a string.


2 Answers

var dateToConvert = "Wed Oct 02 2013 00:00:00 GMT+0100 (GMT Daylight Time)";
var format =        "ddd MMM dd yyyy HH:mm:ss 'GMT'zzz '(GMT Daylight Time)'";

var date = DateTime.ParseExact(dateToConvert, format, CultureInfo.InvariantCulture);

Console.WriteLine(date); //prints 10/2/2013 2:00:00 AM for my locale

You need to specify ending with 'GMT'zzz '(GMT Daylight Time)'

You can use single d in format instead of dd, works fine

You can check demo here

like image 90
Ilya Ivanov Avatar answered Oct 05 '22 18:10

Ilya Ivanov


Thank you. This is exactly what I have done to resolve the question in the last comment above.

int gmtIndex = dateToConvert.IndexOf("G");

string newDate = dateToConvert.Substring(0, gmtIndex).Trim();

value = DateTime.ParseExact(newDate, "ddd MMM dd yyyy HH:mm:ss", CultureInfo.InvariantCulture);
like image 32
t_plusplus Avatar answered Oct 05 '22 17:10

t_plusplus