DateTime.ParseExact And making it work with a custom format - c#

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

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

System.FormatException: String was not recognized as a valid DateTime - when trying to convert MM/DD/YYYY

I have following C# method:
DateTime ConvertStringToDate(string dateInString)
{
try {
//string SSD = dateInString;
//DateTime date = Convert.ToDateTime(SSD);
//string strDate = String.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", date);
//return Convert.ToDateTime(strDate);
return DateTime.ParseExact(dateInString, "MM/dd/yyyy", CultureInfo.InvariantCulture);
}
catch (Exception) { }
return DateTime.Today;
}
The code in comment is another way I tried before.
I am in India and developing an ASP.NET WebForms application for my client in US. On one of its forms my client will enter the date in TextBox like 6/20/2018 which is MM/dd/yyyy format.
But in both the ways I am getting this error: System.FormatException: 'String was not recognized as a valid DateTime.'
I tried many solutions on SO but none of them are working.
return DateTime.ParseExact(dateInString, "M/d/yyyy", CultureInfo.InvariantCulture);
Check it here
The difference between my answer and Fabulous' one is that I also shortened dd to d so if your user writes 6/6/2018 it will work too
Your date format is MM/dd/yyyy and your input doesn't match. It is M/dd/yyyy
Based on your comment, to solve the 6/1/2018 issue, you'll need to do it as follows M/d/yyyy
Your format string is missing the AM/PM deisgnator:
return DateTime.ParseExact
(dateInString + " 12:00:00 AM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
// Here ---------------------------------------------^
Try without concatenation with string " AM"
I was getting the same exception a couple of days ago when it was 9th of July, I simply appended a 0 with 9 to match the date format.
Try appending a 0 in your month to match the MM in your date format
Sometimes your system time and date format is not same as test format you can try to change system date and time format
If you want to convert this (01-01-2022) type of string into date
then try below code.
DateTime date = DateTime.ParseExact("01-01-2022", "MM-dd-yyyy", CultureInfo.InvariantCulture);
If you want to convert this (01/01/2022) type of string into date
then try below code.
DateTime date = DateTime.ParseExact("01-01-2022", "MM/dd/yyyy", CultureInfo.InvariantCulture);

Date Parse triggers error in ASP.NET

I'm trying to parse a date string in mm/dd/yyyy to date type, but it triggers an error saying:
String was not recognized as a valid DateTime.
This is the code I'm using:
Dim mydate As Date
If filter = 4 Then
mydate = Date.ParseExact(datepart, "mm/dd/yy", System.Globalization.DateTimeFormatInfo.InvariantInfo)
End If
I don't understand what I did wrong, any help is appreciated.
You have two little errors in your format string:
DateTime mydate = DateTime.ParseExact("07/27/2016",
"MM/dd/yyyy",
System.Globalization.DateTimeFormatInfo.InvariantInfo);
Months are parsed by "MM" not "mm" (lower case is for minutes)
The four digit year is parsed by "yyyy" not "yy"
Your date format is wrong, use MM/dd/yyyy instead mm/dd/yy try below
Date.ParseExact(datepart, "MM/dd/yyyy", CultureInfo.InvariantCulture)
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date-only value with invariant culture.
string dateString = "06/15/2008";
string format = "d";
var result = DateTime.ParseExact(dateString, format, provider);

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

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

string was not recognized as a valid datetime while Converting Date from Hijri to Gregorian date

I am Trying to Convert Hijri Date into Gregorian Date I was following this article and My Code is as follows :
var cultureInfo = CultureInfo.CreateSpecificCulture("ar-sa");
string date = "19/12/36 12:00:00 ص";
Getting
string was not recognized as a valid datetime
error in below line
DateTime tempDate = DateTime.ParseExact(date, "dd/MM/yyyy", cultureInfo.DateTimeFormat, DateTimeStyles.AllowInnerWhite);
lblDate.Text = tempDate.ToString("dd/MM/yyyy");
I am getting string was not recognized as a valid datetime. Please can somebody tell me whats wrong with this code?
I think I'm on the right way but.. Let's try something at least.
First of all, DateTime values are always in the Gregorian calendar, basically. There's no such thing as "A DateTime in a UmAlQuraCalendar calendar" - which is used by ar-sa culture - you have to use the UmAlQuraCalendar to interpret a DateTime in a particular way.
Second, when you use DateTime.ParseExact for parsing your string, your string and format does match exactly based on culture you use. Since ص
character seems AMDesignator of ar-sa culture, you should provide tt specifier with your time part as well.
string s = "19/12/36 12:00:00 ص";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yy hh:mm:ss tt", CultureInfo.GetCultureInfo("ar-sa"),
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
Note: Since TwoDigitYearMax is 1451 of UmAlQuraCalendar calendar, your 36 will be parsed as 1436 with yy format specifier.
This perfectly parse your question but WAIT! What will be the result? Here it is.
02/10/2015 00:00:00
Why? As I said in the top, you have to use the UmAlQuraCalendar to interpret this DateTime instance.
UmAlQuraCalendar ul = new UmAlQuraCalendar();
Console.WriteLine(ul.GetYear(dt)); // 1436
Console.WriteLine(ul.GetMonth(dt)); // 12
Console.WriteLine(ul.GetDayOfMonth(dt)); // 19

Categories

Resources