I have a string:
string date = "2019-06-06T14:31:55.7316366+03:00";
and I'm trying to map it to DateTime:
var formattedDate = DateTime.ParseExact(date, "dd/MM/yyyy", null)
But I have an exception: "String was not recognized as a valid DateTime."
I would recommend you to use TryParseExact that returns a boolean value indicating if the convert from string to DateTime is possible on a given format. In your case, the format "o" is valid because it includes everything you have on your pattern (see the links bellow). For sample:
string date = "2019-06-06T14:31:55.7316366+03:00";
DateTime dateValue;
if (DateTime.TryParseExact(date, "o", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
{
// it works
Console.WriteLine("Converted '{0}' to {1} ({2}).", date, dateValue,
dateValue.Kind);
}
else
{
Console.WriteLine("Convertion fails");
}
See the working sample: https://dotnetfiddle.net/V8ftPI
You also can use the ParseExact like your original sample.
var formatedDate = DateTime.ParseExact(date, "o", null);
but it can throws an exception if the date string is not on a valid pattern.
Check these links on the documentation about the DateTime.TryParseExact and DateTime formats and see the valid dateTime formats for C# to extract the format you need.
Related
I am reading date from Excel and stored it in a variable In_Date,
formats with which the date is to be compared is stored in Valid_Date_Formats
In_Date = "08/01/2020 00:00:00"
Valid_Date_Formats is an array which stores multiple date formats.
I am checking the format in if condition but it always fails.
If(DateTime.TryParseExact(In_Date, Valid_Date_Formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
DateTime_PlaceHolder))
What am I doing wrong here.
The input string has the following format: dd/MM/yyyy HH:mm:ss, which is missing from Valid_Date_Formats. (I'm assuming the 08 here is the day, because all your other formats start with the date part.)
The following returns the correct date:
DateTime.ParseExact("08/01/2020 00:00:00", new[] { "dd/MM/yyyy HH:mm:ss" }, CultureInfo.InvariantCulture, DateTimeStyles.None)
In response to your comment: I'm not aware of a built-in method that would tell you which exact format string was used. If you really need to find out, I guess you could traverse the formats until you find a match:
string[] formats = new[] { "dd/MM/yyyy", "dd/MM/yyyy HH:mm:ss" };
string input = "08/01/2020 00:00:00";
string usedFormat = null;
DateTime date;
foreach (string format in formats)
{
if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
usedFormat = format;
break;
}
}
Tried the below but it only takes care of one format
string date = "20100102";
DateTime datetime = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);
Instead of
DateTime datetime = DateTime.ParseExact(date, "yyyyMMdd",
CultureInfo.InvariantCulture);
...try:
var dateString = "20100102";
var formats = new String[]{"yyyyMMdd",
"ddMMyyyy"};
DateTime dateValue;
if (DateTime.TryParseExact(dateString, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateValue))
Console.WriteLine ("Success");
MSDN has this to say on DateTime.TryParseExact:
Converts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. The format of the string representation must match at least one of the specified formats exactly. The method returns a value that indicates whether the conversion succeeded.
Tell me more
DateTime.TryParseExact
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").
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.
I am below code in c#, where I am converting my string type format date to datetime, but giving the error.
if (!string.IsNullOrEmpty(SessionDictionary.GetValue("UserDetails", "ExpiryDate")))
{
DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "dd mmm yy", null);
strDate = sitedata.FormatDate(ExpiryDate, TridionDateFormat.ShortDate);
}
else
{
strDate = "-";
}
My SessionDictionary.GetValue("UserDetails", "ExpiryDate") is string type data which returns "31/01/2011 00:00:00" format date, in above code where I am using DateTime.ParseExact it is giving me System.FormatException: String was not recognized as a valid DateTime. error.
Please suggest what is wrong.
Thanks.
The sample date you describe (31/01/2011 00:00:00) looks like a format dd/MM/YYYY HH:mm:ss, so why are you using dd mmm yyyy?
Try
DateTime.ParseExact(..., "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.
For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).
Probably because of mmm(there isn't such month format), try MMM instead.(looks like Feb/Jan/etc)
You are using the wrong format to parse the date. The correct one is:
DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "dd/MM/yyyy hh:mm:ss", null)
Also, if your system date format is set to dd/MM/yyyy you can simply use:
DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "G", null)
Try
DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "g", null);
or see here: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx