2

How do I change 1 date format to another in C# e.g 10/10/2014 to 2014-10-10 (Year-month-day) ?

The user selects a date with a datepicker, then it appears in the textbox but the format is 10/10/2014 (day/month/year). But I'm needing this output to be converted to reflect this format 2014-10-10 (Year-month-day)

Within asp.net-mvc

Code:

@Html.Label("Start", "Start Date:")
@Html.TextBox("Start", string.Empty, new {@id = "Start", @class = "datepicker"})
@Html.Label("endd", "End Date:")
@Html.TextBox("endd", string.Empty, new {@id = "End", @class = "datepicker"})
<input type="submit" value="Apply" id ="DateSelected" />

2 Answers2

3

For c# conversion will be :

public static string convert(string dateValue){
        string pattern = "MM/dd/yyyy";
        DateTime parsedDate; 
        if (DateTime.TryParseExact(dateValue, pattern, null, 
                                   DateTimeStyles.None, out parsedDate)){
            return String.Format("{0:yyyy-MM-dd}",parsedDate);
        }
        return null;
    }

    //usage example
        string dateValue="10/10/2014";
        string converted=convert(dateValue);
        if(converted!=null){
            Console.WriteLine("Converted '{0}' to {1}.", 
                                  dateValue, converted); 
        } 
qwr
  • 3,660
  • 17
  • 29
2

From the jQuery UI datepicker documentation when you set up the date picker, specify the format:

$( ".selector" ).datepicker({ dateFormat: "yy-mm-dd" });
DavidG
  • 113,891
  • 12
  • 217
  • 223