1
string final = Convert.ToString(DateTime.Parse(date, System.Globalization.CultureInfo.InvariantCulture) + TimeSpan.Parse(duration));

Hi, I use the above code to add two date's to eachother. It do work very well on Windows and returns the required format yyyy-MM-dd HH:mm:ss in a correct fashion. HOWEVER, when on Linux building with Mono it returns the following format dd/MM/yyyy HH:mm:ss which is not what I want.

How can I specify that I ONLY want the first formatting and nothing else? I tried playing around with ParseExact but it did not do very well. What I've heard ParseExact should not really be needed for this?

Here is a example of input:

string date = "2014-10-30 10:00:04"; // On windows

string duration = "05:02:10"; // duration to be added to date

Greetings.

3 Answers 3

2

Use ToString("yyyy-MM-dd HH:mm:ss") instead of Convert.ToString.

string date = "2014-10-30 10:00:04";  
string duration = "05:02:10";  
DateTime dt1 = DateTime.Parse(date, CultureInfo.InvariantCulture);
TimeSpan ts = TimeSpan.Parse(duration, CultureInfo.InvariantCulture);
DateTime dtFinal = dt1.Add(ts);
string final = dtFinal.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

Convert.ToString uses your current culture's date separator, use CultureInfo.InvariantCulture.

Read: Custom Date and Time Format Strings

Sign up to request clarification or add additional context in comments.

Comments

2

You can use the ToString() Method of the DateTime object.

var dt = DateTime.Now;
dt.ToString("yyyy-MM-dd HH:mm");

Comments

0

Using your code:

string _final = (DateTime.Parse(date, System.Globalization.CultureInfo.InvariantCulture) + TimeSpan.Parse(duration)).ToString("yyyy-MM-dd HH:mm:ss");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.