21

My app parses a string data, extracts the date and identify the format of the date and convert it to yyyy-MM-dd.

The source date could be anything lime dd-mm-yyyy, dd/mm/yyyy, mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.

Other than attempting different permutations and combinations using switch case, is there any other efficient way to do it?

string sourceDate = "31-08-2012";
String.Format("{0:yyyy-MM-dd}", sourceDate);

The above code simply returns the same sourceDate "31-08-2012".

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
coder
  • 4,121
  • 14
  • 53
  • 88
  • 3
    The problem with not knowing the input format is that `dd/mm/yyyy` and `mm/dd/yyyy` can be interpreted ambiguously. – StuartLC Sep 04 '12 at 05:53
  • @nonnb Exactly! If you have "01/02/2013" what is the correct format? I think the OP should look back and try exploring the problem in more detail. – jfs Sep 04 '12 at 05:55
  • also, is it truly ANY date format, or one of the 5 you mentioned? – Tony Basile Sep 04 '12 at 06:13
  • Does this answer your question? [Format DateTime.Now to yyyy-mm-dd](https://stackoverflow.com/questions/38823758/format-datetime-now-to-yyyy-mm-dd) – Yousha Aleayoub Jan 12 '23 at 10:43

12 Answers12

21
string DateString = "11/12/2009";
IFormatProvider culture = new CultureInfo("en-US", true); 
DateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);

These Links might also Help you

DateTime.ToString() Patterns

String Format for DateTime [C#]

Krishna Thota
  • 6,646
  • 14
  • 54
  • 79
16

Convert your string to DateTime and then use DateTime.ToString("yyyy-MM-dd");

DateTime temp = DateTime.ParseExact(sourceDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
string str = temp.ToString("yyyy-MM-dd");
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
Habib
  • 219,104
  • 29
  • 407
  • 436
7
string sourceDateText = "31-08-2012";
DateTime sourceDate = DateTime.Parse(sourceDateText, "dd-MM-yyyy")
string formatted = sourceDate.ToString("yyyy-MM-dd");
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
rezna
  • 2,243
  • 2
  • 17
  • 16
4

You can write your possible date formats in array and parse date as following:

public static void Main(string[] args)
        {
            string dd = "12/31/2015"; //or 31/12/2015
            DateTime startDate;
            string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy",
                                "dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy", "MM/dd/yyyy"};
            
            DateTime.TryParseExact(dd, formats, 
            System.Globalization.CultureInfo.InvariantCulture,
            System.Globalization.DateTimeStyles.None, out startDate);
                
            Console.WriteLine(startDate.ToString("yyyy-MM-dd"));
            
        }
Zeeshanef
  • 639
  • 3
  • 14
  • 23
  • Out of all the suggestions, this worked for me beautifully. This provides a way to cater multiple formats in one statement and can transform it to the desired format. Thanks – Kumar Shishir Aug 23 '22 at 22:20
3

You can change your Date Format From dd/MM/yyyy to yyyy-MM-dd in following way:

string date = DateTime.ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");

Here, SourceDate is variable in which you will get selected date.

perror
  • 7,071
  • 16
  • 58
  • 85
Amit Singh
  • 210
  • 2
  • 10
1

You will need to parse the input to a DateTime object and then convert it to any text format you want.

If you are not sure what format you will get, you can restrict the user to a fixed format by using validation or datetimePicker, or some other component.

Haris
  • 915
  • 1
  • 11
  • 28
  • It is an xml data parsed in wcf service and updates the database. There is no UI involved. – coder Sep 04 '12 at 06:32
1

This is your primary problem:

The source date could be anything like dd-mm-yyyy, dd/mm/yyyy, mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.

If you're given 01/02/2013, is it Jan 2 or Feb 1? You should solve this problem first and parsing the input will be much easier.

I suggest you take a step back and explore what you are trying to solve in more detail.

jfs
  • 16,758
  • 13
  • 62
  • 88
  • You are right. I just now made it as a setting to avoid complications. The application now knows the input date format. – coder Sep 04 '12 at 06:34
1

Try this code:

 lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");
Raj Baral
  • 661
  • 6
  • 19
Ravi Sharma
  • 362
  • 1
  • 5
1
string sourceDate = "15/06/2021T00.00.00";
DateTime Date = DateTime.Parse(sourceDate)
string date = Date.ToString("yyyy-MM-dd");
Rincy
  • 19
  • 1
  • Welcome to SO @Rincy. Your post ignores the main point of the original question and hence, does not really answer it. The main question is about an input where the format is not fixed. 07/06/2021T00.00.00 can be 6 July or 7 June. – Guy Levy Jun 25 '21 at 12:31
0
if (DateTime.TryParse(datetoparser, out dateValue))
{
   string formatedDate = dateValue.ToString("yyyy-MM-dd");
}
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Zahra Nov 18 '20 at 11:00
0
Convert.toDateTime(sourceDate).toString("yyyy-MM-dd");
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Sameera
  • 41
  • 8
0
Convert.ToDateTime((string)item["LeaveFromDate"]).ToString("dd/MM/yyyy")

This might be helpful