Parse DayTime from 2 formats - c#

I want to parse the date a user puts in. He is allowed to either use the format DD.MM.YYYY or DDMMYYYY.
Unfortunately everything I tried hasn´t worked
DateTime date = new DateTime();
string[] dateFormat = new string[] { "dd.mm.yyyy", "ddmmyyyy" };
string userInput = "30.10.2000" // or "30102000"
date = DateTime.ParseExact(date, dateFormat, null);
"String was not recognized as a valid DateTime" is the exception. I am from Austria but can´t find a culture code that is working.
Thanks

Try this:
DateTime date = DateTime.MinValue;
string[] dateFormats = { "dd.MM.yyyy", "ddMMyyyy" };
string userInput = "30.10.2000"; // or "30102000"
bool isValid = DateTime.TryParseExact(userInput, dateFormats, null, DateTimeStyles.None, out date);
Console.WriteLine($"{date:O}"); // prints date in ISO format
If date is parsed correctly then isValid will be set to true.

It is yyyy for 4 digit years and dd for 2 digit days. It is case-sensitive. You also neglected to pass the dateFormat array into ParseExact, so it will attempt to only do that single format.

Related

input string was not in a correct format date time c#

I am getting a date time from a URL as string and convert it to Date Time format
I get this exception
Input string was not in correct format
And this is my code that i tried
string time = expiredorno;
var result = Convert.ToDateTime(time);
string timeleft = result.ToString("dd/MM/yyyy HH:mm:ss tt", CultureInfo.CurrentCulture);
Note: in the code The variable 'expiredorno' have this value "2021/05/03 14:54:14 PM"
The input string format is likely invalid under the default culture settings. You could set the culture for the convert method as specified here:
https://learn.microsoft.com/en-us/dotnet/api/system.convert.todatetime?view=net-5.0#System_Convert_ToDateTime_System_String_
CultureInfo culture = new CultureInfo("en-US");
Convert.ToDateTime(time, culture);
string time = "2021/05/03 14:54:14 PM";
var result = Convert.ToDateTime(time, CultureInfo.InvariantCulture);
string timeleft = result.ToString("dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
We can try adding CultureInfo.InvariantCulture.
We can use one of the proper parse methods from the DateTime Struct (System) | Microsoft Docs https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=netframework-4.7.2

Why DateTime.TryParseExact is not working?

I am reading date from Excel and stored it in a variable In_Date,
formats with which the date is to be compared is stored in Valid_Date_Formats
In_Date = "08/01/2020 00:00:00"
Valid_Date_Formats is an array which stores multiple date formats.
I am checking the format in if condition but it always fails.
If(DateTime.TryParseExact(In_Date, Valid_Date_Formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
DateTime_PlaceHolder))
What am I doing wrong here.
The input string has the following format: dd/MM/yyyy HH:mm:ss, which is missing from Valid_Date_Formats. (I'm assuming the 08 here is the day, because all your other formats start with the date part.)
The following returns the correct date:
DateTime.ParseExact("08/01/2020 00:00:00", new[] { "dd/MM/yyyy HH:mm:ss" }, CultureInfo.InvariantCulture, DateTimeStyles.None)
In response to your comment: I'm not aware of a built-in method that would tell you which exact format string was used. If you really need to find out, I guess you could traverse the formats until you find a match:
string[] formats = new[] { "dd/MM/yyyy", "dd/MM/yyyy HH:mm:ss" };
string input = "08/01/2020 00:00:00";
string usedFormat = null;
DateTime date;
foreach (string format in formats)
{
if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
usedFormat = format;
break;
}
}

How to find the correct custom format for a date-time string

I read date-time strings from a file in 2 different formats:
19/02/2019 08:24:59
2/17/2019 12:25:46 PM
For the first format the custom format string I wrote is:
string firstDate = "19/02/2019 08:24:59";
string customFormatForFirstDateTimeString = "dd/mm/yyyy hh:mm:ss";
and I use it as follows:
string firstResultingDateAndTime;
bool parsingSuccessful = DateTime.TryParseExact(
firstDate,
customFormatForFirstDateTimeString,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out firstResultingDateAndTime);
The problem is that parsingSuccessful results false.
For the second date-time string, the code is as follows:
string secondDate = "2/17/2019 12:25:46 PM";
string customFormatForSecondDateTimeString = "m/dd/yyy hh:mm:ss PM";
string secondResultingDateAndTime;
parsingSuccessful = DateTime.TryParseExact(
secondDate,
customFormatForSecondDateTimeString,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out secondResultingDateAndTime);
Also here I receive
parsingSuccessful == false;
I reckon that the custom format strings do not fit the date-time strings, but I was not able to figure out why.
Please help.
Thank you in advance.
Well, mm stands for minutes, not months (we have MM for it) that's why dd/mm/yyyy format should be dd/MM/yyyy.
Another issue with hour format where we have hh for 0..12 range (with tt for AM/PM) and HH for 0..23 interval:
string firstDate = "19/02/2019 08:24:59";
// Since we don't have AM / PM we can conclude that hour is in 0..23 range
string customFormatForFirstDateTimeString = "dd/MM/yyyy HH:mm:ss";
string secondDate = "2/17/2019 12:25:46 PM";
string customFormatForSecondDateTimeString = "M/dd/yyyy hh:mm:ss tt";

Parse string to DateType ASP.NET C# exception - The string was not recognized as a valid DateTime

So I have a date which is in this format. My goal is to add 7 days to this string startdate and post it into a database as a string. However, I have to convert it to datetime to allow me to add days to it. I am reading startdate from a database but this is what it looks like.
string startdate = "10-03-2018 03:15PM";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime starttime2 = DateTime.ParseExact(startdate, "MM/dd/yyyy HH:mm tt", culture);
// It is breaking on the above line with the error - The string was not recognized as a valid DateTime.
DateTime endtime2 = starttime2.AddDays(+7);
Anyone able to help me solve this issue? I am new to C# and would appreciate any help at all..
Thank you
You have specified wrong format actually. You should be specifying the following format:
"dd-MM-yyyy hh:mmtt"
as your date is in format :
"10-03-2018 03:15PM"
Assuming that the first number us for day and second is for month, otherwise you can swap those.
You can see more details on the usage of ParseExact here.
Try this:
string startdate = "10-03-2018 03:15PM";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime starttime2 = DateTime.ParseExact(startdate, "dd-MM-yyyy hh:mmtt", culture);
no space between mm and tt. also this is 12 hours format so hh
I think this will help you
public static DateTime AddDaysToMyDate(string date)
{
return DateTime.ParseExact(date, "dd-MM-yyyy hh:mmtt", new CultureInfo("en-US", true)).AddDays(7);
}
Use it as
DateTime newDateTime = AddDaysToMyDate("10-03-2018 03:15PM");

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)

Categories