user979331
user979331

Reputation: 11961

Format a date string using C#

I have a date that is coming from the database like so:

26/01/2016 12:00:00 AM

and I am capturing it as a string

questionItem.DueDate = dataReader[6].ToString();

I am trying to reformat this string so its looks like

2016-01-26

How would I do this?

Upvotes: 0

Views: 6720

Answers (3)

Tyler H
Tyler H

Reputation: 443

Two options:

questionItem.DueDate = new DateTime(dataReader[6]).ToString("yyyy-MM-dd");

Or

questionItem.DueDate = dataReader[6].Split(new string[] { " " }, StringSplitOptions.None)[0].Replace('\\', '-');

Upvotes: 0

Faisal
Faisal

Reputation: 1397

You can specify format like below.

 questionItem.DueDate = Convert.ToDateTime(dataReader[6]).ToString("yyyy-MM-dd");

Check MSDN form DateTime formating.

Upvotes: 6

Neil Busse
Neil Busse

Reputation: 149

Should look something like this

questionItem.DueDate = dataReader[6].ToString("yyyy-MM-dd");

For further readings checkout https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

Upvotes: 3

Related Questions