Milos
Milos

Reputation: 677

Parse date format to DateTime c#

How to parse this string:

 "\"2014-01-02T23:00:00.000Z\"" to DateTime 

This didn't work:

    DateTime? dateTimeFormat= string.IsNullOrEmpty(inputString) ?? (DateTime?)null : DateTime.Parse(inputString);

Upvotes: 2

Views: 9932

Answers (6)

Inshaal Tahir
Inshaal Tahir

Reputation: 41

I've tried almost all of the method/codes in this answer but none of them worked for me. Although, using parts of code of previous answer to this question, I did this and it worked perfectly for me.

var d = "2019-01-11T05:00:00.000Z"; //Date

int year = Convert.ToInt32(d.Substring(0, 4));
int month = Convert.ToInt32(d.Substring(5, 2));
int day = Convert.ToInt32(d.Substring(8, 2));

var time = new DateTime(year, month, day);

I was not concerned with the time. You can add it if you want.

Upvotes: 0

Konrad Kokosa
Konrad Kokosa

Reputation: 16878

You need to specify exact format of you datetime to the DateTime.ParseExact method:

string input = "\"2014-01-02T23:00:00.000Z\"";
var date = DateTime.ParseExact(input, "'\"'yyyy-MM-dd'T'HH:mm:ss.fff'Z\"'", null);

Description of format provided:

'\"'           - match first "
yyyy-MM-dd     - match 2014-01-02
'T'            - match T
HH:mm:ss.fff   - match 23:00:00.000
'Z\"'          - match Z"

Upvotes: 3

arun
arun

Reputation: 85

This will help

string test = "2014-01-02T23:00:00.000Z";
DateTime dt = Convert.ToDateTime(test);

Upvotes: 2

Khan
Khan

Reputation: 342

Try This:

DateTime.ParseExact("2014-01-02T23:00:00.000Z" , "yyyy-MM-DDThh:mm:ssZ",CultureInfo.InvariantCulture);

Maybe this might work.

Add- using System.Globalization;

Upvotes: 0

KillaKem
KillaKem

Reputation: 1025

Reformat the string to put in the proper format, then parse

string =  "\"2014-01-02T23:00:00.000Z\"";
string = substring(3,10) + " " + substring(14,8); //"2014-01-02 23:00:00"
time = DateTime.Parse(string);

Upvotes: 0

Lucky Lefty
Lucky Lefty

Reputation: 347

DateTime.ParseExact(your_date.ToString(), "yyyy-MM-ddTHH:mm:ssZ", null)

Upvotes: 0

Related Questions