I have a WP8 app, which will send the current time to a web service.
I get the datetime string by calling
DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff")
For most users it works great and gives me the correct string like "09/10/2013 04:04:31.415"
. But for some user the resulted string is something like "09/14/2013 07.20.31.371"
, which causes problem in my web service.
Is it because some culture format issue? How can I make sure the result string is delimited by colon instead of dot?
This question is related to
c#
windows-phone-8
Convert Date To String
Use name Space
using System.Globalization;
Code
string date = DateTime.ParseExact(datetext.Text, "dd-MM-yyyy", CultureInfo.InstalledUICulture).ToString("yyyy-MM-dd");
You can use String.Format:
DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"
I bumped into this problem lately with Windows 10 from another direction, and found the answer from @JonSkeet very helpful in solving my problem.
I also did som further research with a test form and found that when the the current culture was set to "no"
or "nb-NO"
at runtime (Thread.CurrentThread.CurrentCulture = new CultureInfo("no");
), the ToString("yyyy-MM-dd HH:mm:ss") call responded differently in Windows 7 and Windows 10. It returned what I expected in Windows 7 and HH.mm.ss in Windows 10!
I think this is a bit scary! Since I believed that a culture was a culture in any Windows version at least.
:
has special meaning: it is The time separator. (Custom Date and Time Format Strings).
Use \
to escape it:
DateTime.ToString(@"MM/dd/yyyy HH\:mm\:ss.fff")
Or use CultureInfo.InvariantCulture
:
DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture)
I would suggest going with the second one, because /
has special meaning as well (it is The date separator.), so you can have problems with that too.
You can use InvariantCulture because your user must be in a culture that uses a dot instead of a colon:
DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);
Source: Stackoverflow.com