Converting string to datetime in C# - 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);

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

Unable to parse DateTime with a custom format

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

Can't remove hidden characters from string

I'm trying to remove hidden characters from a string that represents a date time. I'm using .Net Fiddle and you can see the line that tries to ParseExact fails.
Here is a snippet. Please refer to the fiddle link for working code.
var dateTime = "2015-04-14 07:30:00 PM"; //<= this throws an error from some hidden char
dateTime = Regex.Replace(dateTime, #"[^\w:\s-]", "");
Console.WriteLine(dateTime);
DateTime dateWithTime = DateTime.ParseExact(dateTime, "yyyy-MM-dd HH:mm:ss tt",
CultureInfo.InvariantCulture);
Console.WriteLine("OK");
The HH in the format string refers to the 24-hour clock hours, which doesn't work when using AM/PM in the format string for PM times.
Change HH to hh.
It's not an invisible character. Your use of HH conflicts with your use of tt. HH is 24 hour time, but you are using tt to interpret PM (12 hour time). Change it to hh and it works.
var dateTime = "2015-04-14 07:30:00 PM";
//dateTime = Regex.Replace(dateTime, #"[^\w:\s-]", ""); <= not needed
Console.WriteLine(dateTime);
DateTime dateWithTime = DateTime.ParseExact(dateTime, "yyyy-MM-dd hh:mm:ss tt",
CultureInfo.InvariantCulture);
Console.WriteLine("OK");
You need to change HH to hh.
yyyy-MM-dd hh:mm:ss tt

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

date problem in C#

if i have this in a string : 10/13/2010 8:38:40 AM
how to make it to this: 13/10/2010 08:38:40
thank's in advance
DateTime.ParseExact("10/13/2010 8:38:40 AM","MM/dd/yyyy h:mm:ss tt",CultureInfo.InvariantCulture).ToString("dd/MM/yyyy HH:mm:ss")
edited to make sure 24 hour clock is used in output
Use DateTime.Parse() to convert to a true DateTime object and then use the DateTime.ToString() method to output to the format you desire (code example coming):
var dateTime = DateTime.Parse("10/13/2010 8:38:40 AM");
var formattedString = dateTime.ToString("dd/MM/yyyy HH:mm:ss);
Quick and dirty:
DateTime.Parse("10/13/2010 8:38:40 AM", new CultureInfo("en-US")).ToString(new CultureInfo("en-GB"));
Since I know that those formats are for those cultures. However, you can read more about datetime formatting at:
http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
Standard formatting:
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
Custom formatting:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Or for a more general solution, just pass a format string to DateTime.ToString('formatString'). For example, what you want is DateTime.ToString("dd/MM/yyyy HH:mm:ss"). This allows you to make any format you want.
Example:
DateTime exDT = DateTime.Now;
string exOut = exDT.toString("dd/MM/yyyy HH:mm:ss");
Here's a cheat sheet! You can use ":" where you want it
d Short Date
D Long Date
t Short Time
T Long Time
f Full date and time
F Full date and time (long)
g Default date and time
G Default date and time (long)
M Day / Month
r RFC1123 date
s Sortable date/time
u Universal time, local timezone
Y Month / Year
dd Day
ddd Short Day Name
dddd Full Day Name
hh 2 digit hour
HH 2 digit hour (24 hour)
mm 2 digit minute
MM Month
MMM Short Month name
MMMM Month name
ss seconds
tt AM/PM
yy 2 digit year
yyyy 4 digit year
var strfrom = "10/13/2010 8:38:40 AM";
DateTime dt = DateTime.Parse(strfrom, new CultureInfo("en-US"));
Console.WriteLine(dt.ToString(new CultureInfo("en-GB")));
var curDate = DateTime.Now.ToString() ;
string customDateFormat = Convert.ToDateTime(curDate).ToString("dd/MM/yyyy");
another variant, one one line:
DateTime.Parse("10/13/2010 8:38:40 AM", new CultureInfo("en-US")).ToString("dd/MM/yyyy HH:mm:ss");

Categories