String was not recognized as a valid DateTime. Throws an Exception - c#

I'm trying to convert current date to a specified format.
DateTime date = DateTime.ParseExact(DateTime.Now.ToString(), "yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
I'm receiving the following exception.
String was not recognized as a valid DateTime.
My local TimeZone is (UTC+10:00)Melbourne.
What am I doing wrong here?

Your code (even if it worked), would do nothing. It would simply serialize and deserialize the date. I believe you're looking for this:
string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
It doesn't work because DateTime.Now.ToString() is giving a string like (I happen to be in the same timezone, and presumably have the same culture as you):
14/01/2016 3:54:01 PM
Which is of the format:
dd/MM/yyyy h:mm:ss tt
Which does not match the format you're using: yyyy-MM-dd HH:mm:ss.fff

Try this:
string fm = "yyyy-MM-dd HH:mm:ss.fff";
string str = DateTime.Now.ToString(fm, CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact(str, fm, CultureInfo.InvariantCulture);
EDIT:
A better way to achieve the date in the format would be like
DateTime now = DateTime.Now;
CultureInfo culture = new CultureInfo("en-AU"); //Melbourne
Thread.CurrentThread.CurrentCulture = culture;
Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
IDEONE DEMO

Related

Change DateTime Format {"MM/dd/yyyy"} to {"dd/MM/yyyy"} and time should remain same in Unity

I want to change DateTime now to the Format {"MM/dd/yyyy"} using this code.
string.Format("{0:MM:dd:yyyy}", DateTime.Now)
and saving it.
after getting saved string I get DateTime in format {"MM/dd/yyyy"} . Now I want to convert it in another format so I can Parse to DateTime. when I try to parse MM/dd/yyyy to DateTime got an error
"FormatException: String was not recognized as a valid DateTime."
Thanks in Advance.
You can rather use DateTime.ParseExact which allows you to specify the exact date format you are expeting the input to have.
For example
var now = DateTime.Now;
Debug.Log(now.ToString("dd.MM.yyyy"));
var example1 = now.ToString("MM/dd/yyyy");
Debug.Log(example1);
var readTime1 = DateTime.ParseExact(example1, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Debug.Log(readTime1.ToString("dd.MM.yyyy"));
var example2 = now.ToString("dd/MM/yyyy");
Debug.Log(example2);
var readTime2 = DateTime.ParseExact(example2, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Debug.Log(readTime2.ToString("dd.MM.yyyy"));
See Fiddle
The format is only relevant for display
If you save it in a C# DateTime variable, there is no "format" when saving it, this DateTime is a struct data type which is universal and not bound to any specific format
If you want to use a specific format for parsing, you can use:
// Parse date and time with custom specifier.
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
DateTime myDate = DateTime.ParseExact(dateString, format, provider);
You can use CultureInfo to optimize your format for you needs
If there is a need to save it as "MM/dd/yyyy", your should save it as string
best regards

DateTime.ParseExact And making it work with a custom format

I have a datetime coming back from an text file as a string in the format:
Saturday 15-07-2016 00:55:54
as in
"dddd dd-MM-yyyy HH:mm:ss"
I am trying to convert it to DateTime format using the DateTime.ParseExact, my code is as following:
CultureInfo provider = CultureInfo.InvariantCulture;
string lastLine = File.ReadLines("logon.txt").Last(); //the date string is in the logon.txt
DateTime dt = DateTime.ParseExact(lastLine, "dddd dd-MM-yyyy HH:mm:ss",provider);
return dt;
the exception i get is a System.FormatException : {"String was not recognized as a valid DateTime."}
link to logon txt : https://drive.google.com/file/d/0B1oTQq97VF44Z21pT2FzM01XbU0/view?usp=sharing
any ideas?
The problem is that the date you're showing is Friday, but the string says it should be Saturday. Change the content of the file so instead of "Saturday" it says "Friday" and it should work. It does for me, anyway.
Alternatively, you could change the date part to "16-07-2016" and leave the day of the week "Saturday". Either way it should work.
Here's the code that works for me:
CultureInfo provider = CultureInfo.InvariantCulture;
string lastLine = "Friday 15-07-2016 00:55:54";
DateTime dt = DateTime.ParseExact(lastLine, "dddd dd-MM-yyyy HH:mm:ss", provider);
Console.WriteLine(dt);
It prints out:
7/15/2016 12:55:54 AM

convert to stamp time format from string c#

I use javascript to pick a date and display the format as (11-05-2015 17:37)
and I try to parse it to date time as the code below
DateTime taskDate = Convert.ToDateTime(txtDate.Text);
and save it into my date base like
TO_DATE('" + createOn + "')
its give me and error call "String was not recognized as a valid DateTime."
anyone have any others method to parse it to stamptime ?
the txtDate.Text value is 27-05-2015 09:37.
Convert.ToDateTime uses your current thread culture format when converting from string to datetime.
If string you converting from has another format, you need to use DateTime.ParseExact and explicitly provide appropriate format.
For example, in you case it should be
DateTime taskDate = DateTime.ParseExact("11-05-2015 17:37", "dd-MM-yyyy HH:mm", CultureInfo.InvariantCulture);
Also have a look to custom datetime format strings for your reference.
You can use DateTime.ParseExact or DateTime.TryParseExact
Check below code:
DateTime taskDate = DateTime.ParseExact(txtDate.Text, "dd-MM-yyyy hh:mm", CultureInfo.InvariantCulture);
Or
DateTime taskDate;
if (DateTime.TryParseExact(txtDate.Text, "dd-MM-yyyy hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out taskDate))
{
//code if date valid
}
else
{
//code if date invalid
}

Converting string to date time

I have a date which comes in a string like so:
09/25/2014 09:18:24
I need it like this (yyyy-mm-dd):
2014-09-25 09:18:24
The object that this date goes into is a nullable date.
Tried this does not work:
DateTime formattedDate;
bool result = DateTime.TryParseExact(modifiedDate, "yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out formattedDate);
Any clues?
Thanks in advance.
From DateTime.TryParseExact
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.
In your case, they are not. Use yyyy-MM-dd HH:mm:ss format instead.
string s = "2014-09-25 09:18:24";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
It is a little bit unclear but if your string is 09/25/2014 09:18:24, then you can use MM/dd/yyyy HH:mm:ss format instead. Just a tip, "/" custom format specifier has a special meaning as replace me with current culture or supplied culture date separator. That means, if your CurrentCulture or supplied culture's DateSeparator is not /, your parsing operation will fail even if your format and string matches exactly.
If you have already a DateTime and you want to format it, you can use DateTime.ToString(string) method like;
dt.ToString("yyyy-mm-dd", CultureInfo.InvariantCulture); // 2014-09-25
or
dt.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture); // 2014-09-25 09:18:24
Remember, a DateTime does not have any implicit format. It just contains date and time values. String representations of them have formats.
In answer to your question, to convert it as you prefer, do it like this:
string originalDate = "09/25/2014 09:18:24";
DateTime formattedDate;
if (DateTime.TryParseExact(originalDate, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out formattedDate))
{
string output = formattedDate.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture);
}
And then output will have your desired format.
DateTime dateOf = Convert.ToDateTime("09/25/2014 09:18:24");
string myFormat = "yyyy-mm-dd";
string myDate = dateOf.ToString(myFormat); // output 2014-18-25
Datetime format

Convert timestamp string to DateTime object in c#

I have timestamp strings in the following format 5/1/2012 3:38:27 PM. How do I convert it to a DateTime object in c#
var date = DateTime.ParseExact("5/1/2012 3:38:27 PM",
"M/d/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture);
You input string looks like in en-us format, which is M/d/yyyy h/mm/ss tt. You have to use proper CultureInfo instance while parsing:
var ci = System.Globalization.CultureInfo.GetCultureInfo("en-us");
var value = DateTime.Parse("5/1/2012 3:38:27 PM", ci);
or
var ci = new System.Globalization.CultureInfo("en-us");
Try to use DateTime.ParseExact method like;
string s = "5/1/2012 3:38:27 PM";
DateTime date = DateTime.ParseExact(s, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
Console.WriteLine(date);
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.
Output will be;
01.05.2012 15:38:27
Be aware, this output can change based which Culture you used. Since my Culture is tr-TR, the date operator is . our culture.
Here is a DEMO.
Try the DateTime.ParseExact method
http://www.codeproject.com/Articles/14743/Easy-String-to-DateTime-DateTime-to-String-and-For
this maybe helps you. There you can find a detailled explanation of the ParseExact parameters.

Categories

Resources