Error in "DateTime.ParseExact" when using Nullable DateTime - c#

I have a Nullable DateTime, and I got an error :
Additional information: String was not recognized as a valid DateTime.
I looked at here, here,here and also here . I also tried String.Format("{0:s}", dateTime), but it does not change my DateTime format.My code is like below,
if (person.JsonData.PasswordChangeRequestTime != null)
{
DateTime data;
data = DateTime.ParseExact(((DateTime)person.JsonData.PasswordChangeRequestTime).Date.ToStringDateTime(), "dd'-'MM'-'yyyy HH':'mm':'ss", CultureInfo.InvariantCulture);
person.setColumnValue("passwordchangerequesttime", data);
}
One of my DateTime is like this:
1/1/2015 2:00:00 PM
I want them in a format of
1-1-2015 14:00:00
what is wrong with my DateTime.ParseExact function?
By the way, I do not want to use subString function!

You don't need to do anything.
Your (DateTime)person.JsonData.PasswordChangeRequestTime already a DateTime, what you see this is probably in a debugger or something.
A DateTime does not have any implicit format. It just have date and time values. Format concept only matter when you get it's textual (string) representation which is usually done with DateTime.ToString() method.
If you wanna get exact string representation of it, you can use ToString method with proper format and culture settings like;
((DateTime)person.JsonData.PasswordChangeRequestTime)
.ToString("d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture)
genereates 1/1/2015 2:00:00 PM and
((DateTime)person.JsonData.PasswordChangeRequestTime)
.ToString("d-M-yyyy HH:mm:ss", CultureInfo.InvariantCulture)
generates 1-1-2015 14:00:00 formatted strings.
If your 1/1/2015 2:00:00 PM is string, not a DateTime, you need to parse it to DateTime with proper format first then generate it's string representation with proper format as well.
string s = "1/1/2015 2:00:00 PM";
DateTime dt;
if(DateTime.TryParseExact(s, "d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.ToString("d-M-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
// Generates 1-1-2015 14:00:00
}

Related

How to convert one DateTime format to another?

I have one object {System.DateTime} value is {5/17/2010 12:00:00 AM}.
I want to convert this datetime format to "d-MMM-yyyy",
string msStartDt="5/17/2010 12:00:00 AM";
DateTime.ParseExact(msStartDt, "MM/dd/yyyy HH:mm:ss",CultureInfo.InvariantCulture).ToString("d-MMM-yyyy");
String was not recognized as a valid DateTime.
second parameter of ParseExac() method is a format specifier that defines the required format of msSartDt.
If I change {5/17/2010 12:00:00 AM} to {17-Dec-2010 12:00:00 AM} we need to change 2nd parameter of DateTime.ParseExact()
My question is how we can find programatically the format of msStartDt so we can put in second parameter of DateTime.ParseExact() method.
You need to use
M specifier instead of MM specifier since single digit numbers don't have leading zero
hh specifier instead of HH specifier since you are using 12-hour format
tt specifier for AM/PM designators
string msStartDt = "5/17/2010 12:00:00 AM";
var str = DateTime.ParseExact(msStartDt, "M/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture).ToString("d-MMM-yyyy");
On the other hand, your question is vauge. You said I have one object DateTime value is 5/17/2010 12:00:00 AM but you have a string in your code as it.
If you have already a DateTime, you just need to format it with ToString method. You don't need parsing at all.
DateTime dt = ...
var str = dt.ToString("d-MMM-yyyy", CultureInfo.InvariantCulture);
My question is how we can find programatically the format of msStartDt
so we can put in second parameter of DateTime.ParseExact() method.
It is not possible.
Think about you have a string like 01/02/2015. What is the proper format of this string? It is 1st February or 2nd January? Is it dd/MM/yyyy or MM/dd/yyyy? It is totally ambiguous as you can see. If you have a string formatted, you have to know it's proper format to parse a DateTime.
You need to specify AM/PM in your string format:
DateTime.ParseExact(msStartDt, "M/dd/yyyy hh:mm:ss tt",CultureInfo.InvariantCulture)
also you need to change from HH to hh because HH is for 24h dates
Here you have all datetime fromat constants.
Please try this one:
DateTime.ParseExact(msStartDt, "M/dd/yyyy hh:mm:ss tt",CultureInfo.InvariantCulture);
When we use the ParseExact the format of the string we parse must be exactly the same with the string. In your case you had omitted the AM/PM designator. Furthermore you need to correct the months and hours. For futher information, please have a look here.
You should specify the correct parse format
DateTime.ParseExact(msStartDt, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture).ToString("d-MMM-yyyy")
Firstly, convert your specified date from String to DateTime, then convert to another date format:
string dateString;
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "05/17/2010 12:00:00 AM";
DateTime dt = Convert.ToDateTime(dateString, provider);
Console.WriteLine(dt.ToString("d-MMM-yyyy HH:mm:ss tt"));
See other date time formats in the following link: http://www.csharp-examples.net/string-format-datetime/
Your output should be like the follow screenshot:

How to converting in to time?

I am trying to convert to time from a string
My string are like this "11:45 AM" or "03:19 PM" and i am using
dateTime = DateTime.ParseExact("11:45 AM", "H:mm tt",
System.Globalization.CultureInfo.InvariantCulture);
Then it is getting converted but when i am passing
DateTime.ParseExact("3:19 PM", "H:mm tt",
System.Globalization.CultureInfo.InvariantCulture).ToString();
Getting error as
String was not recognized as a valid DateTime.
I cant understand why it is happening any one have idea then please help me
I would use h instead of H. H is for the 24hr fromat, h for the 12hr format.
DateTime.ParseExact("9:45 PM", "h:mm tt", System.Globalization.CultureInfo.InvariantCulture)
See the full list of format options here.
As you want to parse the 12 hr format and convert it to the 24 hr format then you can just use this
string dt = DateTime.ParseExact("3:19 PM", "h:mm tt",CultureInfo.InvariantCulture).ToString("HH:mm");;
Unfortunately, none of the answers are completely correct.
Ante meridiem and post meridiem belong to the 12-hour clock format. That's why you should never use 24-hour clock format specifiers if your string contains one of them.
That's why you need to use h or hh specifiers, not H or HH. Since your hour part can be with leading zeros, using hh specifier is the best option for both of your string types.
Using the hh:mm tt format will parse your strings successfully.
string s = "03:19 PM";
DateTime dt;
if(DateTime.TryParseExact(s, "hh:mm tt", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.Dump(); // 29.05.2015 15:19:00
}
and
string s = "11:45 AM";
DateTime dt;
if(DateTime.TryParseExact(s, "hh:mm tt", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.Dump(); // 29.05.2015 11:45:00
}
Also, you mentioned the 3:19 PM string in your code example. Since the hour part is single digit, you need to use the h:mm tt format in that case.
Invariant culture requires two-digit hours.

How to convert a date string from "dd-MMM-yy" to "M/dd/yyyy hh:mm:ss tt"?

I need to compare two date format strings:
dateString in "dd-MMM-yy" format
with
referenceDateString in "M/dd/yyyy hh:mm:ss tt" format respectively.
For that, I need to convert the dateString = "dd-MMM-yy" to "M/dd/yyyy hh:mm:ss tt".
However, Got an error while trying to do that:
"Error: string was not recognized as a valid datetime".
The C# code I used given below.
string dateString = "19-Dec-14";
string AsofDate = DateTime.ParseExact(dateString, "M/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
Edit 1:
In the actual code the dateString obtaining after reading a csv file which is supplied as "19-Dec-14", that's why it's in the string format.
Please help, am pretty new to C#. Thanks.
Habib already gave the answer on his comments, I try to add it as an answer;
From DateTime.ParseExact(String, String, IFormatProvider)
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.
In your case, clearly they don't. First, you need to parse your string to DateTime with proper format (which is dd-MMM-yy with an english-based culture), then you can get the string represention of your DateTime with specific format.
string s = "19-Dec-14";
DateTime dt;
if(DateTime.TryParseExact(s, "dd-MMM-yy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.ToString("M/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture).Dump();
// Result will be 12/19/2014 12:00:00 AM
}
It's not entirely clear what you are trying to do, but in order to parse that date you have on the first line, you would use something like this:
DateTime AsofDate = DateTime.ParseExact(dateString, "dd-MMM-yy", System.Globalization.CultureInfo.InvariantCulture);
Note a couple things here: I've changed the data type of AsofDate from string to DateTime because that's what DateTime.ParseExact returns. Also, I've modified the custom format string to match the format of the string you are trying to parse as a date ("19-Dec-14").

Convert custom date to mysql datetime

I have a custom date format that I want to convert to Datetime so I can then insert into my database, I tried using Datetime.ParseExact() But I think I'm misunderstanding something as the code throws a System.FormatException.
I have the following date format from a csv
> 6/11/2014 9:00
and I wish to convert it to the mysql datetime format
> 0000-00-00 00:00:00 OR yyyy-MM-dd HH:mm:ss
Notice they haven't included the seconds in the original date so I am unsure (without appending them to the end) how to set all records to just have "00" for seconds as it is not available.
I tried the following which throws an exception
DateTime myDate = DateTime.ParseExact("6/11/2014 9:00", "yyyy-MM-dd HH:mm",
System.Globalization.CultureInfo.InvariantCulture);
first thing you need to convert string to date time and than convert datetime tos tring
string strd = "6/11/2014 9:00";
DateTime dt ;
//convert datetime string to datetime
if(DateTime.TryParse(strd, out dt))
{
//convert datetime to custom datetime format
Console.WriteLine("The current date and time: {0: yyyy-MM-dd HH:mm:ss}",
dt); ;
}
output
I know this is late to answer that but I'm really surprised none of answer consider to use IFormatProvider to prevent a possible parsing error because of / format specifier or considering your string is a standard date and time format for your CurrentCulture or not so you can or can't use DateTime.TryParse(string, out DateTime) overload directly.
First of all, let's look at what DateTime.ParseExact documentation says:
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case, they don't match. You should use d/MM/yyyy H:mm format to parse your example string with a culture that have / as a DateSeparator. I almost always suggest to use DateTime.TryParseExact method in this kind of situations;
string s = "6/11/2014 9:00";
DateTime dt;
if(DateTime.TryParseExact(s, "d/MM/yyyy H:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
// result will be 2014-11-06 09:00:00
}
If you know formats of your dates, then you can do this:
string stringDate = "6/11/2014 9:00";
//Your date formats of input
string[] dateFormats = new string[]
{
"d/MM/yyyy H:mm",
"dd/MM/yyyy H:mm",
"dd/MM/yyyy HH:mm",
"dd/MM/yyyy H:mm:ss",
"dd/MM/yyyy HH:mm:ss"
/* And other formats */
};
DateTime convertedDate;
bool isSuccessful = DateTime.TryParseExact(stringDate, dateFormats,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out convertedDate);
if (isSuccessful)
{
//If conversion was successful then you can print your date at any format you like
//because you have your date as DateTime object
Console.WriteLine(convertedDate.ToString("dd-MM-yyyy HH:mm:ss")); /* Or other format you want to print */
}
I hope it will be helpful to you.

DateTime.TryParse issue with dates of yyyy-dd-MM format

I have the following date in string format "2011-29-01 12:00 am" . Now I am trying to convert that to datetime format with the following code:
DateTime.TryParse(dateTime, out dt);
But I am alwayws getting dt as {1/1/0001 12:00:00 AM} , Can you please tell me why ? and how can I convert that string to date.
EDIT: I just saw everybody mentioned to use format argument. I will mention now that I can't use the format parameter as I have some setting to select the custom dateformat what user wants, and based on that user is able to get the date in textbox in that format automatically via jQuery datepicker.
This should work based on your example "2011-29-01 12:00 am"
DateTime dt;
DateTime.TryParseExact(dateTime,
"yyyy-dd-MM hh:mm tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
You need to use the ParseExact method. This takes a string as its second argument that specifies the format the datetime is in, for example:
// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
try
{
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
Console.WriteLine("{0} is not in the correct format.", dateString);
}
If the user can specify a format in the UI, then you need to translate that to a string you can pass into this method. You can do that by either allowing the user to enter the format string directly - though this means that the conversion is more likely to fail as they will enter an invalid format string - or having a combo box that presents them with the possible choices and you set up the format strings for these choices.
If it's likely that the input will be incorrect (user input for example) it would be better to use TryParseExact rather than use exceptions to handle the error case:
// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
DateTime result;
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out result))
{
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
else
{
Console.WriteLine("{0} is not in the correct format.", dateString);
}
A better alternative might be to not present the user with a choice of date formats, but use the overload that takes an array of formats:
// A list of possible American date formats - swap M and d for European formats
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
"MM/d/yyyy HH:mm:ss.ffffff" };
string dateString; // The string the date gets read into
try
{
dateValue = DateTime.ParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None);
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
If you read the possible formats out of a configuration file or database then you can add to these as you encounter all the different ways people want to enter dates.
The main drawback with this approach is that you will still have ambiguous dates. The formats are tried in order so no matter what it'll try the European format before the American (or vice versa) and cover anything where the day is less than 13 to a European formatted date even if the user thought they were entering an American formatted date.
Try using safe TryParseExact method
DateTime temp;
string date = "2011-29-01 12:00 am";
DateTime.TryParseExact(date, "yyyy-dd-MM hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out temp);
From DateTime on msdn:
Type: System.DateTime% When this method returns, contains the DateTime
value equivalent to the date and time contained in s, if the
conversion succeeded, or MinValue if the conversion failed. The
conversion fails if the s parameter is null, is an empty string (""),
or does not contain a valid string representation of a date and time.
This parameter is passed uninitialized.
Use parseexact with the format string "yyyy-dd-MM hh:mm tt" instead.
That works:
DateTime dt = DateTime.ParseExact("2011-29-01 12:00 am", "yyyy-dd-MM hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact("11-22-2012 12:00 am", "MM-dd-yyyy hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
If you give the user the opportunity to change the date/time format, then you'll have to create a corresponding format string to use for parsing. If you know the possible date formats (i.e. the user has to select from a list), then this is much easier because you can create those format strings at compile time.
If you let the user do free-format design of the date/time format, then you'll have to create the corresponding DateTime format strings at runtime.

Categories