I convert a DateTime to a string using a custom format:
var s = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
Now, when I try to reverse it:
var dt = DateTime.ParseExact(s, "yyyy/MM/dd hh:mm:ss");
I get an exception about the string not being in a valid format. I even tried to pass CultureInfo.InvariantCulture, but no luck.
Any ideas?
If you use ToString method with one argument, then it uses CurrentCulture as format provider that can change the "/" symbol to specific for your culture ("." for example).
If InvariantCulture is acceptable for you, try to use this code:
var s = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss", CultureInfo.InvariantCulture);
var dt = DateTime.ParseExact(s, "yyyy/MM/dd hh:mm:ss", CultureInfo.InvariantCulture);
I had mistakenly forgotten the last parameter to ParseExact, which whould be CultureInfo.InvariantCulture. In the end, however, the problem was not having HH instead of hh.
Related
I have a string that looks like 5/27/2015 4:49:54 AM
I need it to be in this format: 2015-27-05T04:49:54+08:00
I tried converting it like so but it throws an error:
var convertedDate = DateTime.ParseExact(originalDate, "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",
new CultureInfo("en-US", true));
I also tried converting it like this but it doesn't seem to do anything, convertedDate ends up being the same as originalDate:
var convertedDate = String.Format("{0:u}", originalDate);
You need to parse first, then use your desired format string with ToString translate.
Try this:
string input = "5/27/2015 4:49:54 AM";
DateTime originalDate = DateTime.Parse(input);
string output = originalDate.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK");
You can swap out DateTime.Parse with DateTime.ParseExact if needed. DateTime.Parse will attempt to parse using your system culture. You can be more specific if you need/want to be.
Also, keep in mind that the f in the format string creates a mandatory decimal. To match your prescribed output, you should use F or omit.
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
Try this code.
string inputString = "05/27/2015 04:49:54 AM";
DateTime dt = DateTime.ParseExact(inputString, "M/dd/yyyy H:mm:ss tt",
System.Globalization.CultureInfo.InvariantCulture);
string outputString = dt.ToString("yyyy-MM-ddTHH:mm:sszzz");
Output string will return the value as "2015-05-27T04:49:54+08:00".
First parse the original string to a DateTime. Then format the DateTime to a string of the desired format.
var originalDate = "5/27/2015 4:49:54 AM";
var result = DateTime.ParseExact(originalDate, "M/d/yyyy h:mm:ss tt", CultureInfo.CurrentCulture)
.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'sszzzz");
Console.WriteLine(result);
Outputs
2015-05-27T04:49:54-04:00
Note that that the timezone offset you get will be dependent on the culture of the machine this runs on because it is not specified in the original string.
Try convertedDate.ToString("yyyy-MM-ddThh:mm:sszzz"), date and time settings on your local machine may affect how the output is formatted so you can't always rely on the in-built formatting strings.
To parse "5/27/2015 4:49:54 AM" you should use this format string: "M/d/yyyy h:mm:ss tt"
DateTime convertedDate = DateTime.ParseExact(
"5/27/2015 4:49:54 AM",
"M/d/yyyy h:mm:ss tt",
new CultureInfo("en-US", true));
Then you can use DateTime.ToString with the desired format-string which seems to be "yyyy-dd-MM'T'hh:mm:sszzz" to get 2015-27-05T04:49:54+08:00 as output:
string result = convertedDate.ToString("yyyy-dd-MM'T'hh:mm:sszzz"); // zzz to get UTC offset
See: The "zzz" Custom Format Specifier
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.
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
You can use the ToString() Method of the DateTime object.
var dt = DateTime.Now;
dt.ToString("yyyy-MM-dd HH:mm");
Using your code:
string _final = (DateTime.Parse(date, System.Globalization.CultureInfo.InvariantCulture) + TimeSpan.Parse(duration)).ToString("yyyy-MM-dd HH:mm:ss");
Trying to parse s I get Exception
"String was not recognized as a valid DateTime"
string s = #"07/24/2014 14:46:47";
DateTime dt = DateTime.Parse(s);
System.Globalization.CultureInfo provider =
System.Globalization.CultureInfo.InvariantCulture;
string dateTimeString = #"07/24/2014 14:46:47";
string dateTimeFormat = #"MM/dd/yyyy HH:mm:ss";
var dateTime = DateTime.ParseExact(dateTimeString, dateTimeFormat, provider);
Useful links:
DateTime.ParseExact Method on MSDN
Standard Date and Time Format Strings on MSDN
The "/" custom format specifier on MSDN
Using the Escape Character on MSDN
DateTime myDate = DateTime.ParseExact("7/24/2014 14:46:47",
"MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
As said by Sayse and Sriram Sakthivel you need to pass in the format the string will be in
DateTime.ParseExact(s, "MM-dd-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
string dt = "10/25/2010 11:40:05 PM";
var currentThread = Thread.CurrentThread.CurrentCulture; //ru-RU
DateTime dateTime = DateTime.Parse(dt); //Exception!
How to parse that dt?
UPDATE:
In my case DateTime can be represent as "25.10.2010 11:40:05" or "10/25/2010 11:40:05 PM"
Is these any "generic" method to parse it without changing CurrentCulture?
Use a custom Date and Time format string, using either ParseExact or TryParseExact.
DateTime dateTime;
DateTime.TryParseExact(
dt,
"MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateTime
);
The string cannot be parsed as a Russian DateTime representation since the Russian culture doesn't use AM/PM, hence the use of the use of CultureInfo.InvariantCulture which is a US like culture (it represents no specific culture, but is modeled after the en-US one).
Try using ParseExact instead:
DateTime myDate = DateTime.ParseExact("10/25/2010 11:40:05 PM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
Try DateTime.Parse(dt, CultureInfo.GetCultureInfo("EN-us"))
var result = DateTime.ParseExact(dt,
"MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
To avoid runtime exceptions use safe DateTime.TryParseExact() method, it returns false in case of unsuccessfull parsing rather than throwing the FormatException exception
Russia doesn't use AM and PM as their AM/PM designators, which is at least one reason that would fail. Another is that Russia may not use the "month/day/year" format which is mostly a peculiarity of the US as far as I'm aware. (I can't remember Russia's format strings offhand; I do remember that the genitive month names caused me grief recently, but that's another story...)
I would personally explicitly specify the culture as the invariant culture, and also explicitly specify the format string:
string text = "10/25/2010 11:40:05 PM";
string pattern = "MM/dd/yyyy hh:mm:ss tt";
DateTime dt = DateTime.ParseExact(text, pattern,
CultureInfo.InvariantCulture);
If this might reasonably be expected to fail, you should use DateTime.TryParseExact instead, to handle failure gracefully without involving exceptions.
Try something like this:
dateTime = DateTime.Parse(dt, CultureInfo.CreateSpecificCulture("en-US"));
I have 2 strings: one is date value like "20101127", the second is format "yyyymmdd". How could I extract the date from the value using the given format?
Thanks
Use DateTime.ParseExact:
DateTime time = DateTime.ParseExact("20101127", "yyyyMMdd", null);
null will use the current culture, which is somewhat dangerous. You can also supply a specific culture, for example:
DateTime time = DateTime.ParseExact("20101127", "yyyyMMdd", CultureInfo.InvariantCulture);
Use DateTime.ParseExact(). Note that month is MM, not mm.
var dateValue = DateTime.ParseExact("20101127", "yyyyMMdd",
CultureInfo.InvariantCulture);
Use the ParseExact method.