简体   繁体   中英

Converting Date format from dd/MM/yyyy to MM/dd/yyyy

In our web application, we are supporting the Spanish language. While collecting information we allowing users to input date in dd/MM/yyyy format for Spanish version website and MM/dd/yyyy for English version of the website.

After collecting that information we are sending the whole object to microservices to process. Here I'm trying to convert the dd/MM/yyyy to MM/dd/yyyy before sending out information form my web application.

I'm having trouble converting dd/MM/yyyy to MM/dd/yyyy.

steps I followed to convert format:

User input: 26/02/2020

string effDate = effectivePolicyDate.ToString("MM/dd/yyyy", CultureInfo.CreateSpecificCulture("en-US"));

effectivePolicyDate is user input. from the above code, I'm getting effDate = "02/26/2020"(Getting expected result in a string.)

I need to send date in DateTime format not in string, so tried to convert it into DateTime below.

var date = DateTime.ParseExact(effDate, "MM/dd/yyyy", CultureInfo.InstalledUICulture);

Here I'm trying to parse the date, on date I'm getting 26/02/2020(dd/MM/yyyy) but not MM/dd/yyyy.

var date2 = DateTime.Parse(effDate);

Above line is throwing below exception.

DateTime.Parse("2/26/2021");
'DateTime.Parse("2/26/2021")' threw an exception of type 'System.FormatException'
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2146233033
    HelpLink: null
    InnerException: null
    Message: "String '2/26/2021' was not recognized as a valid DateTime."
    Source: "System.Private.CoreLib"
    StackTrace: "   at System.DateTimeParse.Parse(ReadOnlySpan`1 s, DateTimeFormatInfo dtfi, DateTimeStyles styles)\r\n   at System.DateTime.Parse(String s)"
    TargetSite: {System.DateTime Parse(System.ReadOnlySpan`1[System.Char], System.Globalization.DateTimeFormatInfo, System.Globalization.DateTimeStyles)}
DateTime.Parse("26/2/2021");

I did not find a way to convert date format from dd/MM/yyyy to MM/dd/yyyy, I sent the date as it is and other applications handling. I'm curious to know is there away to convert the format. I'm successful to convert into a string but failing to convert string(MM/dd/yyyy) date to Date property.

Your question is somewhat unclear, but it seems that var date2 = DateTime.Parse(effDate); is the issue. I added two examples using DateTime.Parse in the test below, I hope this will help.

[Test]
public void DateTests()
{
    var expectedDate = new DateTime(2020, 2, 26);

    var date1 = DateTime.Parse("2/26/2020", new CultureInfo("en-US"));
    Assert.AreEqual(expectedDate, date1);

    var date2 = DateTime.Parse("26/2/2020", new CultureInfo("es-ES"));
    Assert.AreEqual(expectedDate, date2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM