Codehelp
Codehelp

Reputation: 4747

DateTime object in a specific format irrespective of the input

I have a ASP.NET MVC app that provides the user to pick a date which is stored into the ViewModel.

This is the code that converts to date object:

viewModel.startDateAndTime = Convert.ToDateTime(buyToday.DealStartDateAndTime);

One of the developers has his system date time set to this format:

24-Feb-2014

On that system he's getting FormatException. I would like to set the date time to use this format:

mm/dd/yyyy

not matter what the setting is on any system..

Tried using this piece of code which does'nt work:

 string startDate = "24-Feb-2014";
 DateTime startDateTime = DateTime.ParseExact(startDate, "mmddyyyy", CultureInfo.InvariantCulture);

Any clues are appreciated. Thanks & Regards.

Upvotes: 1

Views: 759

Answers (3)

Nagaraj S
Nagaraj S

Reputation: 13474

mm returns The minute, from 00 through 59. So use MM The month, from 01 through 12.

string startDate = "24-Feb-2014";
DateTime startDateTime = DateTime.ParseExact(startDate, "ddMMyyyy", CultureInfo.InvariantCulture);

Custom Date and Time Format Strings

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Your input string does not match parsing pattern.

"24-Feb-2014" is much different then mmddyyyy, isn't it?

You can use DateTime.Parse with CultureInfo.InvariantCulture:

string startDate = "24-Feb-2014";
DateTime startDateTime = DateTime.Parse(startDate, CultureInfo.InvariantCulture);

otherwise, with ParseExact the input has to exactly match pattern, so you should pass 24022014 as input. But, just so you know, mm means minutes. For month, use MM :) So pattern should be ddMMyyyy. Check Custom Date and Time Format Strings page on MSDN.

Upvotes: 5

Chris Shao
Chris Shao

Reputation: 8231

try this:

string startDate = "24-Feb-2014";
DateTime startDateTime = DateTime.ParseExact(startDate, "dd-MMM-yyyy",System.Globalization.CultureInfo.InvariantCulture);

Upvotes: 1

Related Questions