Follow us

Thursday, January 20, 2011

Conversion of a string representation of a date and time to its DateTime equivalent

Introduction

Suppose we have assigned a date (dd/MM/yyy format) to a string variable.
// Here format of date is "dd/MM/yyyy"
string date = string.Empty;
date = "21/01/2011";       

    
We can convert the format of the date stored in a string variable using DateTime.ParseExact Method (String, String, IFormatProvider)

Syntax


DateTime.ParseExact() method takes three parameters viz :
  • string 's' containing a date and time to convert
  • Expected format of string 's'
  • An system.IFormatProvider that specifies a culture-specific format information about string 's'

Example

// Here format of date is "dd/MM/yyyy"
string date = string.Empty;
date = "21/01/2011";
date = DateTime.ParseExact(txtDOB.Text, "dd/MM/yyyy", null).ToString("MM/dd/yyyy");
Response.Write(date);
 

Output

01/21/2011


Silimarly, we can convert date stroed in string variable to any other date format as follows:
// Conversion to "yyyy/MM/dd" Format
date = DateTime.ParseExact(txtDOB.Text, "dd/MM/yyyy", null).ToString("yyyy/MM/dd");

// Conversion to "MM/yyyy/dd" Format
date = DateTime.ParseExact(txtDOB.Text, "dd/MM/yyyy", null).ToString("MM/yyyy/dd");



Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

0 comments: on "Conversion of a string representation of a date and time to its DateTime equivalent"

Post a Comment