C# ParseExact not picking the format - c#

I Need help with this simple and silly thing ..
Want to be able to convert this string representation "Oct 9 2017 2:45:67:145PM" to date.
I am using code below:
string strDate = "Oct 9 2017 2:45:67:145PM";
DateTime dtTroubleDate;
dtTroubleDate = DateTime.ParseExact(strDate.ToString(), "MMM d yyyy h:mm:ss:ffftt", CultureInfo.InvariantCulture);
MessageBox.Show("dtTroubleDate String : " + dtTroubleDate.ToString());
This is a C# code within a SSIS package. I am reading the date from a file.
Need to store in the database as 'datetime2'

Never in the history of the Gregorian calendar have been a time with 67 seconds...
This must be a typo in the file itself. The format you are using is OK, but I would recommend using TryParseExact instead of ParseExact for this very reason.
When using ParseExact you are basically saying "I know the string representation of the datetime value will always be in this specific format and I will always be able to parse it.
However, that is rarely the case - as most of the time string representation of datetime values are written by fallible humans, occasionally there will be typos - and that's exactly what the TryParse methods are all about.
string strDate = "Oct 9 2017 2:45:67:145PM";
DateTime dtTroubleDate;
if(DateTime.TryParseExact(
strDate,
"MMM d yyyy h:mm:ss:ffftt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dtTroubleDate))
{
// Datetime is valid
}

Related

ParseExact inverse my day and month

my code below throw an exception as invalid date time. the error occur after i publish it to my server. working find at my developing PC
string str = "27-07-2015 6:15 pm";
DateTime dt = Convert.ToDateTime(DateTime.ParseExact(str, "dd-MM-yyyy h:mm tt", null).ToString("dd-MM-yyyy hh:mm tt"));
it takes '27' as month and '7' as day.
what i did to solve the problem:
i already update the datetime format on that server to dd-MM-yyyy
i double checked the capital and small letter of the date time format.
change the 'null' to 'CultureInfo.InvariantCulture'
change 'pm' to 'PM', 'tt' to 'TT'
read through all the resources i could find on google and stackoverflow, nothing's help.
am i missing something here? i know i did... :(
As #Rawling correctly noted, you're parsing the datetime twice: first, using your custom formatting, and second, using the system's default formatting.
This is silly - you already have the DateTime from the ParseExact method:
string str = "27-07-2015 6:15 pm";
var dt = DateTime.ParseExact(str, "dd-MM-yyyy h:mm tt", null);
That's it, you're done. No need to convert to string again, and parse that once more (and even worse, using the same custom formatting to do the ToString, so the subsequent Convert.ToDateTime is bound to fail anywhere that's not the default datetime formatting).
There are a few possibilities;
Let's analyze your DateTime.ParseExact(str, "dd-MM-yyyy h:mm tt", null) part first. This will be parsed your 27-07-2015 6:15 pm string successfully if;
Your CurrentCulture's TimeSeparator is : and
Your CurrentCulture's PMDesignator is PM (not empty string)
If both are okey, you have successfully parsed a DateTime.
After that, you generate it's textual representation with dd-MM-yyyy hh:mm tt format. And that's still depends on your CurrentCulture, your result might have PM or not. For both case, there is no guaranteed to parse your string with Convert.ToDateTime method because it will be parsed your string only if it is a standard date and time format of your CurrentCulture.
On the other side, what you do doesn't make sense to me. You parse your string first, then you generate string representation of it, then you try to parse this string again. Doesn't make sense, right?
I strongly suspect you just need;
string str = "27-07-2015 6:15 pm";
DateTime dt = DateTime.ParseExact(str, "dd-MM-yyyy h:mm tt", CultureInfo.InvariantCulture);

Can not Parse string to DateTime in Windows Phone 7

I am trying to convert the string to DateTime. But I can not convert.
DateTime dt = DateTime.Parse("16/11/2014", CultureInfo.InvariantCulture);
Console.WriteLine("Date==> " + dt);
The error is FormatException.
My input time format is "dd/MM/yyyy".
Please let me any idea to resolve my problem.
Given that you know your input format, you should specify it with `ParseExact:
DateTime dt = DateTime.ParseExact(text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
I would always recommend being as explicit as you can be about date/time formats. It makes your intention very clear, and avoids the possibility of getting months and days the wrong way round.
As Soner has stated, CultureInfo.InvariantCulture uses MM/dd/yyyy as its short date pattern, as you can validate with:
Console.WriteLine(CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern)
As a mild plug, you might want to consider using my Noda Time project for your date/time handling - aside from anything else, that allows you to treat a date as a date, rather than as a date and time...
Because InvariantCulture doesn't have dd/MM/yyyy as a standard date and time format, but it has MM/dd/yyyy as a standard date and time format.
That's why it thinks your string is MM/dd/yyyy format, but since there is no 16 as a month in Gregorian calender, you get FormatException.
Instead of that, you can use DateTime.TryParseExact method to specify exact format like;
string s = "16/11/2014";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
}

Human readable date to DateTime [duplicate]

This question already has answers here:
DateTime Conversion and Parsing DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")
(3 answers)
Closed 9 years ago.
I need to convert from a "human readable" date format to DateTime, for example:
From: January 20, 2013
To: MM/dd/yyyy
Does anybody know what's the format or if there's one for doing this with DateTime.Parse and providing the format? I just want to check before jumping into a date parser.
Custom Date and Time Format Strings
MMMM dd, yyyy is a format string you're looking for.
Use DateTime.ParseExact or DateTime.TryParseExact to parse the datetime using specific format string.
After parsing you'll be able to print the value in format you want:
string input = "20, 2013";
DateTime value;
if (DateTime.TryParseExact(input, "dd, yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out value))
{
string output = value.ToString("dd/MM/yyyy");
}
I'm not quite sure your goal, but are you trying to format your DateTime based upon which MM/dd/yyyy format that you choose?
If you are you would simply do:
DateTime.Now.ToString(MM/dd/yyy);
DateTime.Now.ToString(MMMM, MM dd, yyyy);
DateTime.Now.ToString(MMMM, MM dd, yyyy hh:mm:ss);
Essentially you have to use these:
Capital MM : Represents the Month, so MMMM (Also creates the Long Date).
Lowercase d : Will represent the day.
Lowercase y: Will represent the year.
Then the hh:mm:ss will actually add an hour, minute, second.
You can also utilize Parse to also ensure it is correctly captured.
Essentially you can easily manage or alter the Format based on whatever you require. MSDN has some great articles on this as well.
Hopefully that helps. Looks like while I was posting a few answers got generated. So your going to get some solid feedback.

converting a string to date in the exact manner

I have a string "11 Jan 2011" which I want to convert to the datatype date (i.e 11 Jan 2011).
I have tried all resources about datetime.parse, datetime.parse exact but all these things gives me the same output 2011/01/11 12:00:00 AM. I really don't understand this behaviour. I tried the following:
1.DateTime date = DateTime.Parse("11 Jan 2011");
2.DateTime date = DateTime.ParseExact("11 Jan 2011" , #"dd MMM yyyy", System.Globalization.CultureInfo.InvariantCulture);
parsing and displaying are not the same thing
you parse the original string to a DateTime object but display results using Date/Time format strings
Both your calls are correct.
A DateTime structure preserves no information about formatting; it just represents the raw date and time.
What you need to do is ensure that when you display your date, you do so in the correct format - e.g. by calling string displayString = date.ToString("dd MMM yyyy");

Troubles parsing DateTime from string

I am currently trying to parse a string that is obtained from an xml that is downloaded from the web every few minutes. The string looks like this:
Thu Jul 12 08:39:56 GMT+0100 2012
At first I just did a string.split and took out everything after the time (GMT+0100 2012) and inserted 2012 after the date.
This worked great until the date changed to:
Thu Jul 12 08:39:56 GMT+0000 2012
So I would like to dynamically pasre the GMT+ whatever as they send me that string in c#.
Any advice would be appreciated.
You can use DateTime.ParseExact with a custom date and time format string:
DateTime.ParseExact("Thu Jul 12 08:39:56 GMT+0000 2012",
"ddd MMM dd hh:mm:ss 'GMT'K yyyy",
CultureInfo.InvariantCulture)
This will throw a format exception if the string and format string do not match exactly, so you may want to use DateTime.TryParseExact that will return a false if it fails.
Instead of DateTime you may want to use DateTimeOffset that preserved timezone information , as #Keith commented - this may be important to your application.
Two things you can do: First, you should be able to use a custom format string with a ParseExact method, either from DateTime or DateTimeOffset (I would use DateTimeOffset if the actual time zone of the stamp is important, and not just the equivalent time in UTC or your local time zone).
Have a look: DateTime custom format string
The format string would probably be something like #"ddd MMM dd HH:mm:ss 'GMT'zzzz yyyy".
However, there's one snag; the .NET time zone offset ("zzzz" or simply "K") always includes a colon between the hour and minute when expressed as a string, which your input strings do not have. There is no way I know of to specify that the time zone offset doesn't/shouldn't have this colon, and I'm pretty sure that trying to parse it without a colon would cause an error.
The simplest workaround is to remove that specific colon from the string prior to parsing it. The code for that given your input is simply to remove the last colon character in the string:
var updatedString = inputString.Remove(inputString.LastIndexOf(':'), 1);
Try DateTime.Parse method to parse your date.
This should work:
XmlConvert.ToDateTime(textBox1.Text, "ddd MMM dd HH:mm:ss 'GMT'zzzz yyyy");

Categories

Resources