How to set/know DateTime class date format interpretion? - c#

I have a particular loop where DateTime instances are to be generated. My problem is on how does the class interpret the input string.
The incoming input strings are of the format MM/dd/yyyy.
Suppose I have "1/17/2014", DateTime would interpret this as MM/dd/yyyy.
But if I have "6/5/2014", how will I be sure that DateTime will parse this with the format MM/dd/yyyy and not dd/MM/yyyy?
EDIT: Inputs may come with the month and/or day in one- or two-digit format.

Because the dates could come in either MM/dd/yyyy or M/d/yyyy then the overload that takes a string[] is the most appropriate:
var dt = DateTime.ParseExact(input,
new[] { "M/d/yyyy", "MM/dd/yyyy" },
CultureInfo.InvariantCulture,
DateTimeStyles.None);
Now, regardless of the zero-padding it will work as expected.

Use the ParseExact function to specify the format :
DateTime d = DateTime.ParseExact("6/5/2014", "M/d/yyyy", CultureInfo.InvariantCulture);
If your input are in MM/dd/yyyy format, you will get 06/05/2014 instead of 6/5/2014. You will then have to use :
DateTime d = DateTime.ParseExact("06/05/2014", "MM/dd/yyyy", CultureInfo.InvariantCulture);
Be sure of your input format if you don't want to have an exception.

take a look at DateTime.ParseExact, which will allow you to specifically match the string

Related

c# convert yyyymmdd text to dd/MM/yyyy

I have some text in rows as yyyymmdd (eg: 20181211) which I need to convert to dd/MM/yyyy
I am using:
cashRow["BusinessDate"] = Convert.ToDateTime(row.Cells[ClosingDate.Index].Value.ToString()).ToString("dd/MM/yyyy");
I get the error "string was not recognized as a valid DateTime.
Any ideas where I am going wrong?
You'll need to use ParseExact (or TryParseExact) to parse the date:
var date = "20181217";
var parsedDate = DateTime.ParseExact(date, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
var formattedDate = parsedDate.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
Here we tell ParseExact to expect our date in yyyyMMdd format, and then we tell it to format the parsed date in dd/MM/yyyy format.
Applying it to your code:
cashRow["BusinessDate"] = DateTime.ParseExact(row.Cells[ClosingDate.Index].Value.ToString(), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
You have to use ParseExact to convert your yyyyMMdd string to DateTime as follows and then everything is okay.
cashRow["BusinessDate"] = DateTime.ParseExact(row.Cells[ClosingDate.Index].Value.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
As you already know the exact format of your input yyyyMMdd (eg: 20181211), just supply it to DateTime.ParseExact() and then call ToString() on the returned DateTime object.
string YourOutput = DateTime.ParseExact(p_dates, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
Try this:
cashRow["BusinessDate"] = row.Cells[ClosingDate.Index].Value.ToString("dd/MM/yyyy");

How to define DateTime parse format for general date format with optional time part?

What is the right DateTime format to parse a date from string in general date format ("G") with optional time part ("d")?
I can have two types of dates:
"12/13/2012 6:30:00 PM"
"3/29/2013"
How to parse them in unified way?
Right now I'm trying to parse with "G" format and then if it not parsed with "d" format.
If your CurrentCulture supports MM/dd/yyyy h:mm:ss tt (I assume your LongTimePattern has h) and M/dd/yyyy (I assume your ShortDatePattern has M) as standard date and time format, using DateTime.TryParse(String, out DateTime) method can solve all your problems.
string s = "";
DateTime dt;
if (DateTime.TryParse(s, out dt))
{
// Your string parsed successfully.
}
If these formats doesn't standard date and time format for your CurrentCulture, using DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) overload can be the best choice because it takes formats part as a string array. That means, you can provide multiple formats and your string will be parsed with first successful match.
string s = "";
string[] formats = { "MM/dd/yyyy h:mm:ss tt", "M/dd/yyyy" };
DateTime dt;
if (DateTime.TryParseExact(s, formats, CultureInfo.CurrentCulture,
DateTimeStyles.None, out dt))
{
// Your string parsed with one of speficied format.
}
Be careful when you parse string that have "/" custom format specifier. It has a special meaning of replace me with current culture or specified culture date separator. That means if your CurrentCulture's DateSeparator property is not /, your parsing operation will fail even if your string and formats are the same format.
Just use DateTime.Parse() or if you want to do a safe parse attempt DateTime.TryParse()
DateTime dt1, dt2;
dt1 = DateTime.Parse("12/13/2012 6:30:00 PM");
dt2 = DateTime.Parse("3/29/2013");
OR
DateTime.TryParse("12/13/2012 6:30:00 PM", out dt1);
DateTime.TryParse("3/29/2013", out dt2);
You only have to use DateTime.ParseExact() or provide the format if it differs from the accepted formats that DateTime.Parse() accepts, or if you only allow one particular format.

Convert string into mm/dd/yyyy format

I have following strings in different formats:
16/05/2014
21-Jun-2014
2014-05-16
16-05-2014
5/19/2014
14 May 2014
I need to convert all the above strings into mm/dd/yyyy format in c#.
I have tried used DateTime.ParseExact as DateTime dt = DateTime.ParseExact("16-05-2014", "mm/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture) in C# but i am getting the exception as "String was not recognized as a valid DateTime".
I have also tried to use to Convert.ToDateTime() but it is also not working.
Is there any method or function that we can write/available in C# that would convert the above string formats into a single date format i.e into "mm/dd/yyyy" format ??
Any help on this would be greatly appreciated.
It fails on the very first term of your format string, which is telling the function to treat the "16" as minutes and to look for hours, minutes, and seconds that don't exist in the input.
You have several different date formats, and so need the ParseExact() overload that accepts several different format strings:
string[] formats= {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd",
"dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"};
string converted = DateTime.ParseExact("16-05-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MM/dd/yyyy");
Also remember that lower case "m"s are for minutes. If you want months, you need an upper case "M". Full documentation on format strings is here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Finally, I suspect you are getting ahead of yourself on formatting the output as a string. Keep these values as DateTime objects for as long as possible, and only format to a string at the last possible moment before showing them to the user. If you really do want a string, at least stick with the ISO 8601 standard format.
Your main problem is that your format string is wrong. A small m is for minute, a big M is for month.
Try to pass all your formats in an array. For example like this
DateTime.ParseExact("16-05-2014",
new[] {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd",
"dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"},
CultureInfo.InvariantCulture, DateTimeStyles.None);
With this you can parse all your formats at once.
For more information about the format settings, see the official docs.
Few things:
Your input date 16/05/2014 doesn't match your format Month/Day/Year - how can there be a 16th month?
Secondly, you're using mm which represents Minutes, not Months. You should use MM.
Finally, your sample string 16-05-2014 doesn't match the format provided, you've used hyphens - instead of forward slashes /
Supply a collection of different formats matching your input:
string[] formats = new [] { "MM/dd/yyyy", "dd-MMM-yyyy",
"yyyy-MM-dd", "dd-MM-yyyy", "dd MMM yyyy" };
DateTime dt = DateTime.ParseExact("05-16-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
You might find the following method useful to accept whatever date format you want and convert it to DateTime:
public DateTime? DTNullable(string DateTimestring, string CurrDateTimeFormat)
{
if (string.IsNullOrEmpty(DateTimestring)) return null;
else
{
DateTime datetimeNotNull;
DateTime.TryParseExact(DateTimestring, CurrDateTimeFormat, null, System.Globalization.DateTimeStyles.None, out datetimeNotNull);
return datetimeNotNull;
}
}
Pass in your desired string to be converted to DateTime along with it's current date time format and this would return you a nullable DateTime. If you're certain that whatever string you're passing in won't be null then you can remove that bit. The reason for it being there is that you can't convert a null to DateTime. In my case I couldn't be certain if it would be or not so I needed the ability to capture nulls as well.
You can use it like this:
DateTime? MyDateTime = DTNullable(MyStartDate, "dd/MM/yyyy");
If you wanted you could alter the method to accept an array of strings and simply iterate through each and return them all in a list if they were of the same format.
As others have pointed out, months are MM not mm (minutes).
On a DateTime object you can call .ToString("MM/dd/yyyy"). Given the strings you have, you can first create new DateTime objects for each string and then call .ToString("MM/dd/yyyy"). For example:
var dateAsMmDdYyyy = DateTime.Now.ToString("MM/dd/yyyy");

Parse string value to datetime value

I need to parse string value to date time value, I have date in this format:
DD.MM.YYYY
I want to parse value in this format:
YYYY-MM-DD
I tried to do it like this:
DateTime.ParseExact(date_req, "yyyy-MM-dd", CultureInfo.InvariantCulture);
But i have an error: String was not recognized as a valid DateTime.
Is there a way to do this?
If you have a string in the format DD.MM.YYYY why are you passing YYYY-MM-DD to your ParseExact function?
Try like this:
string dateStr = "12.06.2012";
DateTime date = DateTime.ParseExact(dateStr, "dd.MM.yyyy", CultureInfo.InvariantCulture);
Then when you want to output this DateTime instance somewhere you could use the YYYY-MM-DD format, like this:
string result = date.ToString("yyyy-MM-dd");
I think what you want to do is parse your dd.MM.yyyy and then display it as yyyy-MM-dd.
You first have to parse the string into a DateTime:
DateTime date = DateTime.ParseExact(date_req, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Now date is a representation of the date that the computer actually understands (before it was just a string). You can now display this object anyway you want:
string yyyyMMdd = date.ToString("yyyy-MM-dd");
string arabic = date.ToString("yyyy-MM-dd", new CultureInfo("ar"));
// and so on
Don't forget that when converting dates from strings to DateTime and back, culture and time zones are worth keeping in mind.
When parsing a date you need to specify the format you want to read, not the format you want as output later.
So use dd.MM.yyyy as argument to ParseExact.
Check DateTime.ParseExact Method (String, String,
IFormatProvider) 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 or an
exception is thrown.
you have to specify format string as DD.MM.YYYY rather than "yyyy-MM-dd".
try this:
DateTime dateValue = DateTime.ParseExact(date_req, "DD.MM.YYYY", CultureInfo.InvariantCulture );
// use this when you need to show that formatted date value
string formattedDate = dateValue.ToString("yyyy-MM-dd");
Better way is that use DateTime.TryParseExact Method, if you want it as date rather than string modify your culture info and date separator.
CultureInfo enUS = new CultureInfo("en-US");
string dateString;
DateTime dateValue;
dateString = "05.01.2009";
if (DateTime.TryParseExact(dateString, "DD.MM.YYYY", enUS,
DateTimeStyles.None, out dateValue))
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
dateValue.Kind);
else
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
First parse it in the existing format then convert to the string format you want.
var date = DateTime.ParseExact(date_req, "dd.MM.yyyy", CultureInfo.InvariantCulture);
var str = date.ToString("yyyy-MM-dd");
You can first convert it to a character array. then you can parse day/month/year separately to integers . You know the indexes of the numbers so this will be easy. after that you can concatenate every element in the way you like.
Error. You have a cake and you want to eat a stake. In order to convince your stomach that that the cake is a stake you have to transform the cake to a stake. This cannot be done. Parsing is about accepting a value as it comes and use a pattern (or more) to translate it to something else and not transform it. So what you want may be right but you ask is wrong.

DateTime - How can i account for different delimiter characters

My application is taking the time now, formatting it into a string, and parsing it back to a valid DateTime value using ParseExact. See below for more details:
DateTime dt = DateTime.Now;
DateTime timeNow = DateTime.Now;
string timeStamp = dt.ToString("MM/dd/yyyy HH:mm:ss");
// To match different countries
if (timeStamp.IndexOf("/") > -1)
{
timeNow = DateTime.ParseExact(timeStamp, "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
}
else if (timeStamp.IndexOf(".") > -1)
{
timeNow = DateTime.ParseExact(timeStamp, "MM.dd.yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
}
Different countries use different date formats. Is there a way to make my application automatically take into account the different formats, rather than having to make a condition for each one that appears?
Thanks for any help,
Evan
If your application is using a string representation for dates internally, I would suggest using the Sortable format specifier when outputting it. That way, you always know that you can read it back using ParseExact and the "s" format specifier.
The only time you should output dates in any other format is when you need to display them for the user, or when some other program requires them in a particular format.
As #Mike Christensen pointed out in his comment, different locales will interpret dates differently. The default output for many European countries is DD/MM/YYYY, whereas in the U.S. it's usually MM/DD/YYYY. If you take the different locales into account, then there will be ambiguity.
You can pass an array of format specifiers with as many formats as you want to support.
string[] formats = new [] { "MM/dd/yyyy HH:mm:ss", "MM.dd.yyyy HH:mm:ss" };
DateTime d = DateTime.ParseExact
(
timestamp, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
However, since you say you are generating the strings yourself, why don't you just make sure you always format them using the InvariantCulture:
string timestamp = dt.ToString("MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);

Categories

Resources