Unable to parse DateTime with a custom format - c#

After reading some other similar questions and trying their suggestions, I'm still unable to get my time to parse into a DateTime-
string time1 = File.ReadAllText(#"C:\Reminders\Reminder1Time.txt");
DateTime dt1 = DateTime.ParseExact(time1, "hh:mm:tt", CultureInfo.InvariantCulture);
dateTimePicker1.Value = dt1;
time1 is a string value of 9:00 AM Other questions have mentioned to use ParseExact to specify a custom format, but it's still not parsing.
The error I get thrown is on the second line
String was not recognized as a valid DateTime.
How would I get the dateTimePicker1 to display the value from the time1 string?

Looks like a stray colon and an extra h if you are expecting a 12 hour clock 1-12 without a leading zero and the AM PM marker with whitespace.
Try: h:mm tt
All of the formatting options are buried in the documentation, here.

var datefromFile = File.ReadAllText(FILELOCATION);
var format = "dd-MM-yyy hh:mm:ss,fff";
var formattedDateTime = DateTime.ParseExact(dateFromFile, format, CultureInfo.InvariantCulture);
Make your format Explicit, remember dd for date capital MM for month and yyyy for year. hh for hour mm for minutes and ss for seconds.
MSDN Formats:
https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

Related

Convert String to DateTime(yyyy-mm-dd)

I'm parsing date from server, date is in this format 6/16/2016 3:15:29 PM Could you help me please convert date to 2016-06-16?
I tried:
DateTime date = DateTime.ParseExact(datestring, "MM/dd/yyyy h-m-s t", System.Globalization.CultureInfo.InvariantCulture);
string formattedDate = date.ToString("yyyy-MM-dd")
but it's giving me error.
You've got 3 problems
You're not using the correct time separators
You're using only one t when you need two
You're using two M when you only need one
Try
DateTime date = DateTime.ParseExact(datestring, "M/d/yyyy h:m:s tt", System.Globalization.CultureInfo.InvariantCulture);
string formattedDate = date.ToString("yyyy-MM-dd");
The reason you need only one M is because MM expects a leading zero. Since the values of the date and time are delimited it's better to use the single versions for month, day, minutes, and seconds because they will work for values with or without leading zeros.
To execute DateTime.ParseExact() format of the input string and the format string must be the same. try this:
DateTime date = DateTime.ParseExact(datestring, "M/dd/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
string formattedDate = date.ToString("yyyy-MM-dd");
These are interesting in the given input string(6/16/2016 3:15:29 PM):
The month is represented in single digit so it should be M instead for MM. We use MM if it is specified as 06.
Same in the case of Hours too. It should be h instead for normal hh
There is a single space in between Date and Time as well as Time and PM.
So we must consider all of these while generating the Format-string for ParseExact

Converting string to datetime in C#

There are several threads on similar topic with several solution but none of them are marked as answer.
I have a string and would like to convert into DateTime
string str = "12-3-2013 12-09-10 PM";
DateTime dt = DateTime.ParseExact(str, "MM-dd-yyyy HH-mm-ss tt", new CultureInfo("en-US"));
This gives an error. Is there something to do with CultureInfo? How does CultureInfo affect the output?
dd: The day of the month, from 01 through 31.
d: The day of the month, from 1 through 31.
For sure day is not dd as is using a single digit. Also, you need to change HH by hh or remove am/pm.
Try with this
MM-d-yyyy hh-mm-ss tt
You might need to change MM by M but it's impossible to say with provided example.
string str = "12-3-2013 12-09-10 PM";
Convert.ToDateTime(str);

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..

Datetime format Issue: String was not recognized as a valid DateTime

I want to format the input string into MM/dd/yyyy hh:mm:ss format in C#.
The input string is in format MM/dd/yyyy hh:mm:ss
For example :"04/30/2013 23:00"
I tried Convert.ToDateTime() function, but it considers 4 as date and 3 as month which is not what I want. Actually month is 04 and date is 03.
I tried DateTime.ParseExact() function also, But getting Exception.
I am getting error:
String was not recognized as a valid DateTime.
Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss).
Also, you need to specify H instead of h if you are using 24 hour times:
DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)
See here for more information:
Custom Date and Time Format Strings
You can use DateTime.ParseExact() method.
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.
DateTime date = DateTime.ParseExact("04/30/2013 23:00",
"MM/dd/yyyy HH:mm",
CultureInfo.InvariantCulture);
Here is a DEMO.
hh is for 12-hour clock from 01 to 12, HH is for 24-hour clock from 00 to 23.
For more information, check Custom Date and Time Format Strings
try this:
string strTime = "04/30/2013 23:00";
DateTime dtTime;
if(DateTime.TryParseExact(strTime, "MM/dd/yyyy HH:mm",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtTime))
{
Console.WriteLine(dtTime);
}
This can also be the problem if your string is 6/15/2019. DateTime Parse expects it to be 06/15/2019.
So first split it by slash
var dateParts = "6/15/2019"
var month = dateParts[0].PadLeft(2, '0');
var day = dateParts[1].PadLeft(2, '0');
var year = dateParts[2]
var properFormat = month + "/" +day +"/" + year;
Now you can use DateTime.Parse(properFormat, "MM/dd/yyyy"). It is very strange but this is only thing working for me.
change the culture and try out like this might work for you
string[] formats= { "MM/dd/yyyy HH:mm" }
var dateTime = DateTime.ParseExact("04/30/2013 23:00",
formats, new CultureInfo("en-US"), DateTimeStyles.None);
Check for details : DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)
DateTime dt1 = DateTime.ParseExact([YourDate], "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).
Below code worked for me:
string _stDate = Convert.ToDateTime(DateTime.Today.AddMonths(-12)).ToString("MM/dd/yyyy");
String format ="MM/dd/yyyy";
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
DateTime _Startdate = DateTime.ParseExact(_stDate, format, culture);
You may use this type format (get formatted data from sql server)
FORMAT(convert(datetime,'16/04/2018 10:52:20',103),'dd/MM/yyyy HH:mm:ss', 'en-us')
CONVERT(VARCHAR,convert(datetime,'16/04/2018 10:52:20',103), 120)

How can I get this DateTime format in .NET

I'm trying to format some DateTime into this W3C DateTime format :-
Complete date plus hours and minutes:
eg. YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
where:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
I originally had this...
var myDateTime = someDateTime.ToString("s",
System.Globalization.CultureInfo.InvariantCulture);
But that results in a string of :
2011-08-31T08:46:00
Can anyone help?
You want "o":
var myDateTime = someDateTime.ToString("o",
System.Globalization.CultureInfo.InvariantCulture);
Use the following:
yourDateTime.ToString( "yyyy-MM-ddTHH:mmK", CultureInfo.InvariantCulture );
Here is more than you'll ever want to know on DateTime formats:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
I believe you want
"yyyy-MM-ddTHH:mmK"
Note:
HH rather than hh to be 24 hour
K to specify the time zone; this relies on the DateTime.Kind being UTC or local; unspecified will end up with an empty string
You should also use CultureInfo.InvariantCulture to make sure no funky culture information is used. (You could quote the - and : as an alternative, but I'd use the invariant culture to make sure.)
You can format it like this:
someDateTime.ToString("yyyy-MM-dd");
Here's the documentation of the 'standard' supported datetime format strings:
http://msdn.microsoft.com/en-us/library/az4se3k1(v=VS.100).aspx
someDateTime.ToUniversalTime().ToString("u");
Will get you pretty close => '2011-09-02 10:22:48Z'. If that isn't good enough, then you can create a custom format string that includes the "T" (see 'Custom Date and Time Format Strings').

Categories