Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert YYYYMMDD string date to a datetime value [duplicate]

Tags:

c#

.net

datetime

Possible Duplicate:
Convert string to DateTime in c#

A question

I got a string value that actually get from directoryInfo. What i wanted to accomplish is to convert the string value to a date value for making comparison.

The folder name is sample like this C:\FOLD\20111120 and properly another folder path is like this C:\FOLD\20111021

20111120 is actually a date format. I am trying to convert it into date format to made some comparison decide to deleting the whole directory or not.

I think i shall paste my code here

DirectoryInfo dir = new DirectoryInfo(_FolderPath);  foreach (DirectoryInfo f in dir.GetDirectories()) {      String folderName = f.ToString();      DateTime ConDt = Convert.ToDateTime(folderName);      Console.WriteLine(ConDt);      Console.WriteLine(ConDt.GetType());    //Console.WriteLine(folderName.GetType());    //Console.WriteLine(f.GetType()); } 

I tried with Convert.toDatetime() and i get error that unable to made the converstion.How can i do so with this?

like image 437
Worgon Avatar asked Nov 21 '11 03:11

Worgon


People also ask

How do you convert date format from Yyyymmdd to yyyy-mm-dd in SQL?

Convert Char 'yyyymmdd' back to Date data types in SQL Server. Now, convert the Character format 'yyyymmdd' to a Date and DateTime data type using CAST and CONVERT. --A. Cast and Convert datatype DATE: SELECT [CharDate], CAST([CharDate] AS DATE) as 'Date-CAST', CONVERT(DATE,[CharDate]) as 'Date-CONVERT' FROM [dbo].

How do I change the date format in Yyyymmdd in SQL?

mm/dd/yyyy corresponds to U.S. standard so if you convert to date using 101 value and then to varchar using 112 for ISO date get the expected result.


1 Answers

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120",                                    "yyyyMMdd",                                     CultureInfo.InvariantCulture); 

OR

string str = "20111021"; string[] format = {"yyyyMMdd"}; DateTime date;  if (DateTime.TryParseExact(str,                             format,                             System.Globalization.CultureInfo.InvariantCulture,                            System.Globalization.DateTimeStyles.None,                             out date)) {      //valid } 
like image 178
KV Prajapati Avatar answered Sep 21 '22 21:09

KV Prajapati