Recognize DateTime String as valid when containing day names in C# - c#

When a date string has the day of the week attached to it, TryParse fails:
DateTime d;
string dateString = "Tuesday May 1, 2012 9:00 AM";
return DateTime.TryParse(dateString, out d); // returns false
What is the best way to deal with this so that I can safely determine it IS a date, and furthermore convert it to such?

You need to tell TryParseExact what format to look for:
DateTime d;
string dateString = "Tuesday May 1, 2012 9:00 AM";
return DateTime.TryParseExact(
dateString,
"dddd MMMM d, yyyy h:mm tt",
System.Globalization.CultureInfo.CurrentCulture,
System.Globalization.DateTimeStyles.None,
out d
);

This should do the trick :)
// Parse date and time with custom specifier.
string dateValue = "Tuesday May 1, 2012 9:00 AM";
string pattern = "dddd MMMM d, yyyy h:mm tt";
DateTime parsedDate;
if (DateTime.TryParseExact(dateValue, pattern, null,
DateTimeStyles.None, out parsedDate))
Console.WriteLine("Converted '{0}' to {1:d}.",
dateValue, parsedDate);
else
Console.WriteLine("Unable to convert '{0}' to a date and time.",
dateValue);
Reference
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Related

Convert string with long month name to DateTime

I have this string July 1, 2021 9:10 AM and I'm trying to parse it into a DateTime variable.
This isn't working for me. ST is a variable that has the string representation of the date and time.
var Event = DateTime.ParseExact(ST, "MMMM dd, yyyy h:mm tt", CultureInfo.InvariantCulture);
You are using the wrong day format. For a month day without a leading zero, you should use the following:
var Event = DateTime.ParseExact(ST, "MMMM d, yyyy h:mm tt", CultureInfo.InvariantCulture);

Convert dd/MM/yyyy HH:mm tt to MM/dd/yyyy HH:mm tt in C#

I want to convert string as : "25/12/2017 4:00 PM" to "12/25/2017 4:00 PM". My code :
var TDXRSC = "25/12/2017 4:00 PM";
DateTime.ParseExact(TDXRSC, "dd/MM/yyyy hh:mm tt", CultureInfo.InvariantCulture);
But it's not working.
The issue is your date format expected is dd/MM/yyyy hh:mm tt but the reference date only has a single digit hour 4. You are probably better off not expect leading zeros for days, months or hours.
Try..
var TDXRSC = "25/12/2017 4:00 PM";
var input = DateTime.ParseExact(TDXRSC, "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture);
This will also still parse 2 digit hours. So var TDXRSC = "25/12/2017 12:00 PM"; will still parse correctly.
var TDXRSC = "25/12/2017 4:00 PM";
var input = DateTime.ParseExact(TDXRSC, "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture);
var output = input.ToString("MM/dd/yyyy h:mm tt");
When you call ParseExact you're telling the compiler what format the incoming date is. You can then use ToString() method to provide a format for a string representation of the parsed date.
Hope that .TryParseExtract will be more safe to use for conversion, use like the following:
var dateString = "25/12/2017 4:00 PM";
DateTime inputDate;
if(DateTime.TryParseExact(dateString, "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out inputDate))
{
var output = inputDate.ToString("MM/dd/yyyy hh:mm tt");
Console.WriteLine(output);
}
else
{
Console.WriteLine("Conversion failed");
}
Working Example
var TDXRSC = "25/12/2017 4:00 PM";
DateTime date = Convert.ToDateTime(TDXRSC);
string Format = date.ToString("MM/dd/yyyy h:mm tt");

How to find exact format of a date string?

I need to know exact date format that will perse the string 16-Aug-78 12:00:00 AM. I have tried various string like "ss-MMM-yy hh:mm:ss". Is there any way for finding it to converting to any general format. I am using CultureInfo.InvariantCulture class.
Your string format is wrong. It has to match your string format exactly. You can use dd-MMM-yy hh:mm:ss tt format instead.
Here an example in LINQPad.
string s = "16-Aug-78 12:00:00 AM";
var date = DateTime.ParseExact(s, "dd-MMM-yy hh:mm:ss tt",
CultureInfo.InvariantCulture);
date.Dump();
Custom Date and Time Format Strings
Or, since dd-MMM-yy hh:mm:ss tt is a standart date and time format for InvariantCulture, you can directly DateTime.Parse method like;
string s = "16-Aug-78 12:00:00 AM";
var date = DateTime.Parse(s, CultureInfo.InvariantCulture);
date.Dump();
Here a demonstration.
Is there any way for finding it to converting to any general format?
There is no way to get format of a string except you create your own formatting. Only you can know what is your string format exactly, computer can't.
For example; 01/02/2014 can be 1 February 2014 or 2 January 2014 depends on which custom format you can parse it.
Try as below
var dstring = "16-Aug-78 12:00:00 AM";
DateTime result;
var matchingCulture = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(ci => DateTime.TryParse(dstring, ci, DateTimeStyles.None, out result))
You have wrong format string, you are using ss for day it should be dd. This article Custom Date and Time Format Strings explains what you need for custom format.
Use
"dd-MMM-yy hh:mm:ss tt"
Instead of
"ss-MMM-yy hh:mm:ss"
You can use DateTime.ParseExact to parse the string.
DateTime dt = DateTime.ParseExact("16-Aug-78 12:00:00 AM", "dd-MMM-yy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None);
You can try with DateTime.TryParseExact():
string strDate = "16-Aug-78 12:00:00 AM";
DateTime datDate;
if(DateTime.TryParseExact(strDate , new string[] {"dd-MMM-yy hh:mm:ss tt" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
Console.WriteLine(datDate);
}
else
{
Console.WriteLine("Error in datetime format");
}

How do I convert a string to Date Time in a particular format in C#?

I'm trying to convert "1/7/2014 1:37 PM" (which is a string) to "01/07/2014 13:37" (DateTime format). What would be the best way to do this?
This is what I've got
string dateString = "1/27/2014 1:37 PM";
string format = "MM/dd/yyyy HH:mm";
DateTime dt;
bool temp = DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Console.WriteLine("bool = {0}, dt ={1}", temp, dt);
And my output is
bool = False, dt =1/1/0001 12:00:00 AM
Much thanks.
EDIT:
It's not just for the string I specified. Adding a few more cases - The LHS should get parsed exactly to the RHS
1/7/2014 1:37 PM -> 01/07/2014 13:37
11/27/2014 1:40 AM -> 11/27/2014 01:40
1/12/2014 2:05 PM -> 01/12/2014 14:05
Essentially, the input string does not have leading zeros and time is in 12 hour format and the output should have leading zeros where needed and should display the time in 24 hour format
I've tried giving
string format = "MM/dd/yyyy HH:mm tt";
but that also gives the same wrong output
bool = False, dt =1/1/0001 12:00:00 AM
Four things to change:
You need lowercase h for hours if you use the am/pm designator
You need a single h if the hour can be 1
You need to add tt for the am/pm designator
You need a single M for the month since it's 1
string dateString = "1/27/2014 1:37 PM";
string format = "M/dd/yyyy h:mm tt";
DateTime dt;
bool temp = DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Console.Write("temp: {0} date:{1}", temp, dt); // temp: True date:1/27/2014 1:37:00 PM
See: The "tt" Custom Format Specifier
Update: acccording to your edit:
I also need to convert it back to string in a specific format. It should have leading zeros and time is in 12 hour format and the output should have leading zeros where needed and should display the time in 24 hour format
1/7/2014 1:37 PM -> 01/07/2014 13:37
11/27/2014 1:40 AM -> 11/27/2014 01:40
1/12/2014 2:05 PM -> 01/12/2014 14:05
Then you can use this format string: MM/dd/yyyy HH:mm in DateTime.ToString with CultureInfo.InvariantCulture. Note that i've used uppercase HH for 24h hour format:
string output = dt.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
You need InvariantCulture, otherwise / will be replaced with the actual date-separator of your current culture (f.e. . in germany).
See: The "/" Custom Format Specifier
Maybe you can try like this
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
Console.WriteLine(String.Format("{0:MM/dd/yyyy}", dt));
You should be using
lowercase h rather than H as the time is in 12-, not 24-hour
one h rather than two as you don't have a leading zero on the hour
one M rather than two as you don't have a leading zero on the month
tt to match AM or PM.
Custom Date and Time Format Strings
You can use
Datetime dtDate = DateTime.PareExact(dt,"DateFormat of dt",cultureInfo.InavriantCulture);
Try This...
static void Main(string[] args)
{
string dateString = "1/27/2014 1:37 PM";
string format = "MM/dd/yyyy HH:mm";
DateTime dt2 = Convert.ToDateTime(dateString);
Console.WriteLine(dt2.ToString(format));
Console.ReadLine();
}
This may help:-
DateTime txtmyDate = DateTime.ParseExact(dateString "MM/dd/yyyy hh:mm",
CultureInfo.InvariantCulture);
From DateTime.TryParseExact method
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format, culture-specific
format information, and style. The format of the string representation
must match the specified format exactly.
In your case, it is not.
MM format is for 01 to 12, use M format which is 1 to 12.
HH format is for 00 to 23, use h format instead which is 1 to 12.
Also you are missing tt format which is for AM/PM designator.
string str = "1/27/2014 1:37 PM";
string format = "M/dd/yyyy h:mm tt";
DateTime dt;
bool result = DateTime.TryParseExact(str,
format,
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt);
Console.WriteLine(result);
Output will be
True
Here a demonstration.
Your format is wrong. You are missing the AM/PM:
string format = "M/dd/yyyy h:mm tt";
Notice the tt part which is required in order to be able to properly parse the date. Also I would recommend you adding error checking:
string dateString = "1/27/2014 1:37 PM";
string format = "M/dd/yyyy h:mm tt";
DateTime dt;
bool temp = DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
if (temp)
{
Console.WriteLine("bool = {0}, dt = {1:M/dd/yyyy h:mm}", temp, dt);
}
else
{
Console.WriteLine("Unable to parse date: {0}", dateString);
}

Checking Date format from a string in C#

I want to check whether a string contains dates such as 1/01/2000 and 10/01/2000 in dd/MM/yyyy format.
So far I have tried this.
DateTime dDate = DateTime.Parse(inputString);
string.Format("{0:d/MM/yyyy}", dDate);
But how can I check if that format is correct to throw an exception?
string inputString = "2000-02-02";
DateTime dDate;
if (DateTime.TryParse(inputString, out dDate))
{
String.Format("{0:d/MM/yyyy}", dDate);
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}
you can use DateTime.ParseExact with the format string
DateTime dt = DateTime.ParseExact(inputString, formatString, System.Globalization.CultureInfo.InvariantCulture);
Above will throw an exception if the given string not in given format.
use DateTime.TryParseExact if you don't need exception in case of format incorrect but you can check the return value of that method to identify whether parsing value success or not.
check Custom Date and Time Format Strings
I think one of the solutions is to use DateTime.ParseExact or DateTime.TryParseExact
DateTime.ParseExact(dateString, format, provider);
source: http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
https://msdn.microsoft.com/es-es/library/h9b85w22(v=vs.110).aspx
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM",
"5/1/2009 6:32:00", "05/01/2009 06:32",
"05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"};
DateTime dateValue;
foreach (string dateString in dateStrings)
{
if (DateTime.TryParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
You can use below IsValidDate():
public static bool IsValidDate(string value, string[] dateFormats)
{
DateTime tempDate;
bool validDate = DateTime.TryParseExact(value, dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, ref tempDate);
if (validDate)
return true;
else
return false;
}
And you can pass in the value and date formats. For example:
var data = "02-08-2019";
var dateFormats = {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}
if (IsValidDate(data, dateFormats))
{
//Do something
}
else
{
//Do something else
}
you could always try:
Regex r = new Regex(#"\d{2}/\d{2}/\d{4}");
r.isMatch(inputString);
this will check that the string is in the format "02/02/2002"
you may need a bit more if you want to ensure that it is a valid date like dd/mm/yyyy
Use an array of valid dates format, check docs:
string[] formats = { "d/MM/yyyy", "dd/MM/yyyy" };
DateTime parsedDate;
var isValidFormat= DateTime.TryParseExact(inputString, formats, new CultureInfo("en-US"), DateTimeStyles.None, out parsedDate);
if(isValidFormat)
{
string.Format("{0:d/MM/yyyy}", parsedDate);
}
else
{
// maybe throw an Exception
}
Try this
DateTime dDate;
dDate = DateTime.TryParse(inputString);
String.Format("{0:d/MM/yyyy}", dDate);
see this link for more info. http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx

Categories

Resources