8

I would like to have my end result in date format as per the specified format i.e YYMMDD how can i get this from a string given as below

   string s="110326";  
Vivekh
  • 4,141
  • 11
  • 57
  • 102
  • 1
    take a look here. http://stackoverflow.com/questions/336226/string-to-datetime-conversion-in-c – sgtz Jul 19 '11 at 12:38

3 Answers3

16

From string to date:

DateTime d = DateTime.ParseExact(s, "yyMMdd", CultureInfo.InvariantCulture);

Or the other way around:

string s = d.ToString("yyMMdd");

Also see this article: Custom Date and Time Format Strings

Sven
  • 21,903
  • 4
  • 56
  • 63
  • How about the provider for ParesExtract – Vivekh Jul 19 '11 at 12:41
  • 1
    No Overload for 2 parameters you need to provide the culture info – Manatherin Jul 19 '11 at 12:42
  • 1
    @Vivekh: sorry, I forgot that `ParseExact` required that parameter. I edited the answer. `InvariantCulture` has the advantage of always giving the same result regardless of the user's regional settings. If you want the result to differ based on the user's region, use `CultureInfo.CurrentCulture` instead. – Sven Jul 19 '11 at 12:44
5
DateTime dateTime = DateTime.ParseExact(s, "yyMMdd", CultureInfo.InvariantCulture);

although id recommend

DateTime dateTime;
if (DateTime.TryParseExact(s, "yyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dateTime))
{
    // Process
}
else
{
    // Handle Invalid Date
}
Manatherin
  • 4,169
  • 5
  • 36
  • 52
2

To convert DateTime to some format, you could do,

 string str = DateTime.Now.ToString("yyMMdd");

To convert string Date in some format to DateTime object, you could do

DateTime dt = DateTime.ParseExact(str, "yyMMdd", null);  //Let str="110719"
FIre Panda
  • 6,537
  • 2
  • 25
  • 38