Hanumantha
Hanumantha

Reputation: 117

How to get date format in required format like 'dd/MM/yyyy' , 'MMddyyyy', MMM, etc

I have date in 'MM/dd/yyyy' format and I need to get date format according input format. Input format will be anyone of 'MMddyyyy', 'yyyy-MM-dd' , MM, MMM, MMMM, yyyy.

Format:'MMddyyyy':: Output Should be: '02232015'

Format:'yyyy-MM-dd':: Output Should be: '2015-02-23'

Format:'yyyy/MM/dd':: Output Should be: '2015/02/23'

Format:'MM':: Output Should be: '02'

Format:'MMM':: Output Should be: 'Feb'

Format:'MMMM':: Output Should be: 'February'

I am trying with

var dateTime = DateTime.ParseExact(date, format, new System.Globalization.CultureInfo("en-US"), System.Globalization.DateTimeStyles.None);

But it is not working. It give invalid date format error.

So can anyone help me to achieve this.

Upvotes: 0

Views: 2326

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98750

I think you are confusing about parsing a string to a DateTime with getting a specific string representation of a DateTime.

If you wanna get a textual representation of a DateTime (like 2015-02-23, 2015/02/23 and February as you said), you can use .ToString() method with an english-based culture.

For your string results with order, you can get them as;

yourDateTimevalue.ToString("MMddyyyy", new CultureInfo("en-US")); // 02232015
yourDateTimevalue.ToString("yyyy-MM-dd", new CultureInfo("en-US")); // 2015-02-23
yourDateTimevalue.ToString("yyyy/MM/dd", new CultureInfo("en-US")); // 2015/02/23
yourDateTimevalue.ToString("MM", new CultureInfo("en-US")); // 02
yourDateTimevalue.ToString("MMM", new CultureInfo("en-US")); // Feb
yourDateTimevalue.ToString("MMMM", new CultureInfo("en-US")); // February

If you try to say like; you have these formatted strings and do you wanna parse these formatted strings to DateTime, you can use this DateTime.ParseExact overload that takes string[] as a format.

var formats = new string[]
{
     "MMddyyyy",
     "yyyy-MM-dd",
     "yyyy/MM/dd",
     "MM",
     "MMM",
     "MMMM"
}

var dateTime = DateTime.ParseExact(date, formats, new CultureInfo("en-US"), DateTimeStyles.None);

Upvotes: 4

Jam
Jam

Reputation: 339

Try this!

string format="MMddyyyy";
DateTime.Now().ToString(format);

Upvotes: 0

User1234
User1234

Reputation: 511

You can use the ToString() with format

DateTime.Now.ToString("MMddyyyy")

Upvotes: 0

Related Questions