hashim
hashim

Reputation: 91

Converting a String to DateTime with new format

How do you convert a string such as 13.11.2017 into a DateTime with that format 13/11/2017

I tried several ways but i didn't get solution .

string Arrival = Request.QueryString["Arrival"];//13.11.2017
DateTime datee = DateTime.ParseExact(Arrival , "dd/MM/yyyy", null);

here is updated code i split the string :

            string Arrival = Request.QueryString["Arrival"];//13.11.2017
      string year = Arrival.Split('.')[2];
                   string month = Arrival.Split('.')[1];
                        string day = Arrival.Split('.')[0];
                        string date = day + "/" + month + "/" + year;
                        DateTime datee = DateTime.ParseExact(date, "dd/MM/yyyy", null);

Upvotes: 0

Views: 643

Answers (3)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241525

Observe:

// the input string
string inputString = "13.11.2017";

// parse the input string with a specific format to create a DateTime
DateTime dt = DateTime.ParseExact(inputString, "dd.MM.yyyy", CultureInfo.InvariantCulture);

// create a string from the DateTime using a different specific format
string outputString = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

// output the string
Console.WriteLine(outputString);  // "13/11/2017"

Note that a DateTime itself does not have any particular format. A format only comes into play when going to or from a string.

Also note that by using the invariant culture here, we are avoiding any issues that may arise if the current culture was one that used different date separators or a different calendar system.

Upvotes: 1

codejockie
codejockie

Reputation: 10864

using System.Text.RegularExpressions;

string Arrival = Request.QueryString["Arrival"]; // 13.11.2017
string dateString = Regex.Replace(Arrival, @"\.", "/"); // 13/11/2017
DateTime date = DateTime.ParseExact(dateString , "dd/MM/yyyy", null); // 11/13/2017 00:00:00

Upvotes: 0

Andrew Myhalchuk
Andrew Myhalchuk

Reputation: 26

Had the same problem with Russian locale. Currently using ISO format everywhere to avoid incorrect DateTime understandings (like MM.dd when you mean dd.MM).

public static string ToIsoStr(this DateTime dateTime)
    {
        return dateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
    }

Your task will be solved with

return dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

Upvotes: 0

Related Questions