String to DateTime conversion as per specified format
Asked Answered
E

3

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";  
Ectogenous answered 19/7, 2011 at 12:35 Comment(1)
take a look here. #336726Firebird
F
17

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

Faxon answered 19/7, 2011 at 12:38 Comment(3)
How about the provider for ParesExtractEctogenous
No Overload for 2 parameters you need to provide the culture infoCrossbench
@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.Faxon
C
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
}
Crossbench answered 19/7, 2011 at 12:41 Comment(0)
V
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"
Visually answered 19/7, 2011 at 12:38 Comment(1)
I asked string to Datetime conversionEctogenous

© 2022 - 2024 — McMap. All rights reserved.