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";
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";
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
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 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
}
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"
© 2022 - 2024 — McMap. All rights reserved.