C# Win. form - Convert String to DateTime [duplicate] - c#

This question already has answers here:
Parse datetime in multiple formats
(7 answers)
Closed 5 years ago.
I have multiple input in string like the following:-
05/09/2017
05/09/2017 13:56 PM
05/09/2017 01:56 PM
05/09/2017 13:56:00
05/09/2017 01:56:00 PM
Now how do i convert the above examples into DateTime format (dd/MM/yyyy hh:mm:ss tt).
I have already tried
ParseExact - It gives error when the user gives 05/09/2017 as value (because the format doesn't match)
DateTime.ParseExact(ValueByuser, "dd/MM/yyyy HH:mm:ss tt", null);
TryParse - The problem with it is that it uses the LocalFormat of the computer like if the computer has set to "MM/dd/yyyy" then it produces output in the same format
DateTime.TryParse(DatePass, out Dtp);

You could use the ParseExact or TryParseExact overload that accepts an array of formats, and pass all the formats you want to support. E.g.
var formats = new[]
{
"dd/MM/yyyy",
"dd/MM/yyyy HH:mm",
"dd/MM/yyyy HH:mm tt",
"dd/MM/yyyy HH:mm:ss",
"dd/MM/yyyy HH:mm:ss tt",
};
You should also specify CultureInfo.InvariantCulture as your format provider, e.g.:
var d = DateTime.ParseExact(s,
formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
I believe the above will match all your sample inputs except the second (05/09/2017 13:56 PM) which I assume is a typo and should be 05/09/2017 13:56 without the am/pm indicator.

You could do something like the following;
string dd = "05 / 09 / 2017 13:56:00";
string newdate = dd.Replace("/", "-");
DateTime DT = DateTime.Parse(newdate);

Related

Why DateTime TryParse is returning date as {01/01/0001 00:00:00}? [duplicate]

This question already has answers here:
How do I format a DateTime in a different format?
(2 answers)
Closed 3 years ago.
I am doing this
string[] formats = { "yyyy-MM-dd" };
DateTime outDate;
DateTime.TryParseExact(DateTime.Now.ToString(),
formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out outDate);
interfaceoperation.LogDate = outDate;
interfaceoperation.LogTime = outDate;
LogDate and LogTime are of type DateTime.
But it returns outdate value as {01/01/0001 00:00:00}.
Why?
I think the problem is in the format of the dates, we will have to add the correct format of your date.
DateTime.TryParseExact(DateTime.Now.ToString(), DateTime.Now.GetDateTimeFormats(),
new CultureInfo("en-US"),
DateTimeStyles.None, out outDate);
or we will have to add the correct format of your date.
Or you can retrieve it directly from the wafer you use date:
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"};
Well, DateTime.TryParseExact returns false and DateTime.MinValue (which is 01/01/0001 00:00:00) whenever it fails to parse the given string.
https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=netframework-4.8
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 either the
s or format parameter is null, is an empty string, or does not contain
a date and time that correspond to the pattern specified in format.
This parameter is passed uninitialized.
It seems, you want more formats to be mentioned:
// Test value
// Something like "10/08/2019 2:47:58 PM"
string value = DateTime.Now.ToString(CultureInfo.GetCultureInfo("en-US"));
...
string[] formats = {
"R", // RFC1123 e.g. 2019-10-08T14:39:47
"yyyy-M-d",
"yyyy-M-d H:m:s",
"M/d/yyyy", // en-US special: date only
"M/d/yyyy H:m:s", // en-US special: date and 24 hour time
"M/d/yyyy h:m:s tt", // en-US special: date and 12 hour time
};
DateTime outDate;
if (DateTime.TryParseExact(value,
formats,
CultureInfo.GetCultureInfo("en-US"),
DateTimeStyles.None, out outDate)) {
// Parsing succeeded
interfaceoperation.LogDate = outDate;
interfaceoperation.LogTime = outDate;
}
else
{
// Parsing failed
}

DateTime.ParseExact Giving Un Expected Error [duplicate]

This question already has answers here:
Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"
(7 answers)
Closed 4 years ago.
I have some problem for which I am unable to find the solution.
Here is my code
string DateString = System.DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt");
string Format = "dd/MM/yyyy hh:mm:ss tt";
DateTime DT = DateTime.ParseExact(DateString, Format, CultureInfo.InvariantCulture);
string DTE = DT.ToString("dd/MM/yyyy");
The code is extracting an Error which I am pasting below. Please tell me what exactly is the problem (My System Date and Time has been set to 3/29/2018 like this and I don't want to change it at all) here is the error
Error Picture
During DateTime conversion to string, you should use CultureInfo.InvariantCulture also. If you do not this, DateString is converted as your machine culture, but you convert back again culture invariant. This may leads problem.
For example: when I use your code, DateString has "OS" value agains to tt field, after than I try to convert into DateTime with CultureInvariant, OS cannot be solved.
string DateString = System.DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
string Format = "dd/MM/yyyy hh:mm:ss tt";
DateTime DT = DateTime.ParseExact(DateString, Format, CultureInfo.InvariantCulture);
string DTE = DT.ToString("dd/MM/yyyy");

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.

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.

convert string to datetime format invalid System.Datetime

I have been trying many different solutions found here but none works. I want to convert the string to the format of dd/MM/yyyy
editField["ExpiryTime"] = "5/19/2011 12:00:00 AM";
DateTime dt = DateTime.ParseExact(editField["ExpiryTime"].ToString(), "dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
But I always get an error of invalid System.DateTime. Pleaes help!
Use CultureInfo.InvariantCulture to avoid culture issues like invalid date separators and this format:
M/dd/yyyy hh:mm:ss tt
Uppercase M is for months, dd are the days, yyyy the four digit years. Lowercase hh are the hours in 12h format(required in combination with AM/PM), mm are the minutes, ss the seconds and tt the AM/PM designator.
string input = editField["ExpiryTime"].ToString(); // "5/19/2011 12:00:00 AM"
DateTime dt = DateTime.ParseExact(input, "M/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
I want to convert the string to the format of dd/MM/yyyy
Then use ToString in the same way, CultureInfo.InvariantCulture forces / as date separator, without it will be replaced with your current culture's date-separator:
string result = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
If you need it as string, then you should try this
var dt = string.Format("{0:dd/MM/yyyy}",DateTime.Now);
Note: Also check your local system date time format. If it mismatches with the used one , still you might experience the same exception..

Categories