C# Date Parse Exact Issue - c#

The following code produces an error, any ideas why?
string dateFormatString = "dd.MM.yyyy HH:mm:ss";
string properDate = DateTime.ParseExact(DateTime.Now.ToString() , dateFormatString , null ).ToString()
Error is: String is not recognised as a valid date and time.

DateTime.Now.ToString() formats the date using the current culture. You need to specify the same format: DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") that's expected by the ParseExact function.

You just need this - rest is piece of cake.
http://john-sheehan.com/blog/wp-content/uploads/msnet-formatting-strings.pdf
and this http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

Does your local culture write dates as "dd.MM.yyyy HH:mm:ss" ? Simply: if the date's ToString() doesn't produce this layout, then it won't parse cleanly - and ParseExact is not very forgiving.
I'm wondering if you actually want to call:
string s = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss");

You could simply do:
string dateFormatString = "dd/MM/yyyy HH:mm:ss";
string properDate = DateTime.Now.ToString(dateFormatString);
EDIT: According to your comments, you are trying to match the format to that common in the Czech Republic. You should use CultureInfo to do do that:
string properDate = DateTime.Now.ToString(new CultureInfo("cs-CZ"));

Related

Formatting Date time to Specific Format

I am trying to convert the DateTime to following Format.
2015-06-11 07:14:03.930
I have tried with ,
string plannedStartTime = startTime.ToString("o");
output:2015-06-12T16:54:47.3206929+05:30
and
string plannedStartTime = startTime.ToString("u");
output:2015-06-12 16:56:57Z
Not getting any formatters from MSDN
Any other Formatters?
all you need is a right format string
try using this startTime.ToString("yyyy-MM-dd HH:mm:ss.fff")
There is no standard date and time format for your output. You need to use custom date and time format specifiers with a culture that have : as a TimeSeparator like InvariantCulture;
string plannedStartTime = startTime.ToString("yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture);
If your CurrentCulture already have : as a TimeSeparator, you don't need to pass second parameter in ToString method.
Hope this is what your asking for
string plannedStartTime = startTime.ToString("yyyy-MM-dd HH:mm:ss.fff");

DateTime.TryParseExact only working in "One Way"

Scope:
I have been trying to develop a super-tolerant DateTime.Parse routine, so I decided to give most "widely-used" formats a try to better understand the format masks.
Problem:
I have defined a specific format (String) which I use as myDate.ToString(format), and it works wonders. The problem is, If I get this same String (result of the .ToString(format) operation), and feed it back to DateTime.TryParseExact (...) it fails.
Code / Test:
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
// Defining Format and Testing it via "DateTime.ToString(format)"
string format = "MM/dd/yyyy HH:mm:ss tt";
string dtNow = DateTime.Now.ToString (format);
Console.WriteLine (dtNow);
// Trying to Parse DateTime on the same Format defined Above
DateTime time;
if (DateTime.TryParseExact (dtNow, format, provider, System.Globalization.DateTimeStyles.None, out time))
{
// If TryParseExact Worked
Console.WriteLine ("Result: " + time.ToString ());
}
else
{
// If TryParseExact Failed
Console.WriteLine ("Failed to Parse Date");
}
Output is : "Failed to Parse Date".
Question:
Why can I use the format string to format a certain date as text, but I can't use the same format to feed the string back to a date object ?
EDIT:
I have added part of my method to this example, and I would like to know why the "ParseDate" method fails to return a proper date, given that the "String" is in the right format.
Since you use DateTime.ToString() method without any IFormatProvider, this method will use your CurrentCulture settings.
That's why your
string dtNow = DateTime.Now.ToString (format);
line might generate a different string representation than MM/dd/yyyy HH:mm:ss tt format.
Three things can cause this issue;
Your CurrentCulture has a different DateSeparator than /
Your CurrentCulture has a different TimeSeparator than :
Your CurrentCulture has a different or empty string as a AMDesignator and/or PMDesignator
Since you try to parse your string with provider (which is InvariantCulture) on your DateTime.TryParseExact method, generate your string based on that provider as well.
string dtNow = DateTime.Now.ToString(format, provider);
You told your CurrentCulture is pt-BR and this culture has empty string "" as a AMDesignator and PMDesignator. That's why your dtNow string will not have any AM or PM designator on it's representation part.
Here a demonstration.

How to Convert a Date String with Format "dd/MM/yyyy" to OS Current Culture Date Format

A string has the value in "dd/MM/yyyy" format like "04/10/2012". This should be converted to a Date w.r.t Current Culture of OS.
I have tried below string with Korean as Current Culture of OS in which date format is yyyy-MM-dd, my code is not getting correct Month value, it interchange the month value with day:
Input: "04/10/2012"
Output: 2012-04-10
Code:
DateTime DT;
string dt = "04/10/2012";
DateTimeFormatInfo DateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
DT = Convert.ToDateTime(String.Format ("{0:"+DateInfo .ShortDatePattern +"}", dt.Trim ()), CultureInfo .CurrentCulture);
MessageBox.Show("Date: " + DT.ToShortDateString());
How I can fix that ?
It looks to me like you need to parse it with a fixed format, I think you are currently parsing it with a format other than "dd/MM/yyyy" and because the date is ambiguous (as in, month and day can be interchanged without causing invalid dates) the format is simply switching the month and day value. When you then go to output it, it looks reversed.
Use DateTime.ParseExact to force the parsing format and then use the built-in current culture sensitive string output methods on DateTime to get a formatted string:
var date = DateTime.ParseExact("04/10/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture);
MessageBox.Show("Date: " + date.ToShortDateString()); // Assumes current culture is controlling format
Since your input string is in a fixed format, you should parse it in that format:
DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);
If you string has the format dd/MM/yyyy then you have to use DateTime.ParseExact with the specified format:
DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Anything else will try an interpret the string according to the current culture's rules - which, as you have found, will fail.
why not use ToShortDateTimeString()

DateTime Conversion and Parsing DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")

I store some DateTime in a CSV log with:
DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")
When I try to read it I found something like:
"05/15/2012 10:09:28.650"
The problem is when I try to cast it as a DateTime again...
DateTime.Parse("05/15/2012 10:09:28.650");
Throws an Exception "Invalid DateTime" or something like that...
How can I properly re-read the DateTime?
You can use DateTime.ParseExact:
string format = "MM/dd/yyyy hh:mm:ss.fff";
DateTime d = DateTime.ParseExact("05/15/2012 10:09:28.650",
format,
System.Globalization.CultureInfo.InvariantCulture);
Standard Date and Time Format Strings
use DateTime.ParseExact with specifying the format
String dateStr=DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff");
DateTime date = DateTime.ParseExact(dateStr,"MM/dd/yyyy hh:mm:ss.fff",System.Globalization.CultureInfo.InvariantCulture);
You should use this method to parse your string. You would have to make a class, imlementing IFormatProvider, but if you want to use a custom DateTime format, it's the best method I can think of.

C# Date Parse Exact mindate issues

I have the following function
DateTime fromDateParam = DateTime.ParseExact(Convert.ToString(DateTime.MinValue),"dd.MM.yyyy HH:mm:ss",null);
It says input string not recognised as a valid date.
Any ideas how I can get any the min date recognised to parse exact?
Well you're converting the original time to a string using the default formatting, but then you're specifying custom formatting for the parsing.
If you specify a format string using DateTime.ToString(format) and keep the format consistent, it works fine:
string formatString = "dd.MM.yyyy HH:mm:ss";
string text = DateTime.MinValue.ToString(formatString);
Console.WriteLine(text);
DateTime fromDateParam = DateTime.ParseExact(text, formatString, null);
In other words (continuing Skeet's answer), Convert.ToString(DateTime.MinValue) is based on current/default CultureInfo, etc.

Categories

Resources