Sunday, March 8, 2009

Converting between dd/mm/yyyy and mm/dd/yyyy in C# asp.net

Convert Date from any format to any format
I came across some problem while converting dates in C# between dd/mm/yyyy and mm/dd/yyyy.

Was struggling with this for a long time and got it in one of the sites. here is the solution :

You can change the from to format and see your results.

Courtesy : Kushaal.net


//For ex., Convert MM/dd/YYYY to dd/MM/yyyy

string date = "03/27/2008"; //format is MM/dd/yyyy

DateTimeFormatInfo dateTimeFormatterProvider = DateTimeFormatInfo.CurrentInfo.Clone() as DateTimeFormatInfo;

dateTimeFormatterProvider.ShortDatePattern = "MM/dd/yyyy"; //source date format

DateTime dateTime = DateTime.Parse(date, dateTimeFormatterProvider);

string formatted = dateTime.ToString("dd/MM/yyyy"); //write the format in which you want the date tobe converted

Response.Write("
" + formatted);

2 comments:

  1. If you want to convert string to specific datetime format then culture info has important role else you may get "FormatException"
    See following:
    http://urenjoy.blogspot.com/2009/03/string-to-datetime-formatexception-and.html

    ReplyDelete
  2. Your This Solution Rocks dude..
    bt can u tell me how can i conver ANY date format to dd/mm/yyyy in C#
    plz help if possible @
    bokyashinde@yahoo.co.in

    ReplyDelete