How do I format a DateTime in a different format? - c#

I have a string representing a date in a certain format, that I wish to format differently. Someone told me to use DateTime.(Try)ParseExact, so I did:
var dateString = "2016-02-26";
var formatString = "dd/MM/yyyy";
var parsedDate = DateTime.ParseExact(dateString, formatString, null);
You see, I want to format the date as dd/MM/yyyy, so 26/02/2016. However, this code throws a FormatException:
String was not recognized as a valid DateTime.
How can I format a DateTime differently?

First of all, DateTimes have no format. A DateTime holds a moment in time and a flag indicating whether that moment is Local, Utc or Unspecified.
The only moment a DateTime gets formatted, is when you output its value as a string.
The format string you provide to (Try)ParseExact is the format that the date(time) string to parse is in. See MSDN: Custom Date and Time Format Strings to learn how you can write your own format string.
So the code you're looking for to parse that string is this, and again, make sure the format string matches the format of the input date string exactly:
var dateString = "2016-02-26";
var formatString = "yyyy-MM-dd";
var parsedDate = DateTime.ParseExact(dateString, formatString, null);
Now parsedDate holds a DateTime value that you can output in your desired format (and note that you'll have to escape the /, as it'll be interpreted as "the date separator character for the current culture", as explained in above MSDN link):
var formattedDate = parsedDate.ToString("dd\\/MM\\/yyyy");
This will format the date in the desired format:
26/02/2016

You can use this for String date
DateTime.ParseExact(dateString, format, provider);
and for provider value
CultureInfo provider = CultureInfo.InvariantCulture;
as mentioned in Microsoft documentation

Related

Convert String to Date Time C#

I'm new to c# how can I convert my input string in to DateTime.
_toDate = 5/22/2015
I cannt use
DateTime.ParseExact(_toDate, "yyyy-MM-dd", null);
Or
Convert.ToDateTime(_toDate)
throw an exception String was not recognized as a valid DateTime.
Note : String shold be excact the same as above.
Appreciate your reply
Clearly, your string and format does not match.
From documentation;
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.
You need to use M/dd/yyyy with a culture that has / as a DateSeparator like InvariantCulture .
string _toDate = "5/22/2015";
DateTime myDate = DateTime.ParseExact(_toDate, "M/dd/yyyy", CultureInfo.InvariantCulture);
When you use null as an IFormatProvider, it's threaded as your CurrentCulture and if your CurrentCulture doesn't have / as a DateSeparator, you will get FormatException because / custom format specifier has a special meaning as replace me with current culture or supplied culture date separator.

Convert to dateTime from string (arabic culture to english)

string strHijdt ="29-02-1435";
DateTime hdt = DateTime.ParseExact(strHijdt, "dd/MMM/yyyy HH:MI24",
CultureInfo.InvariantCulture);
Getting error while convert to string("29-02-1435") to datetime
2/1435 has 28 days only
so, below will work
string aa="28-02-1435";
DateTime hdt = DateTime.ParseExact(aa, "dd-MM-yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(hdt.ToLongDateString());
DEMO
since you have given input as 29-02-1435 even you provide correct date time format (dd-MM-yyyy) you will get error for the invalid date
Two problems here:
1. As mentioned above, expected format for does not match string (there is no time, different separator)
2. If your date string is in Hijri calendar, you should either provide correct culture explicitly or use system culture (pass null for IFormatProvider):
string strHijdt = "29-02-1435";
var culture = CultureInfo.GetCultureInfo("ar-SA");
DateTime hdt = DateTime.ParseExact(strHijdt, "dd-MM-yyyy", culture);

Console application string was not recognised as valid datetime

I have a excel sheet in which am taking a date column in this format "23/8/11 01:33:01:PM"
and am inserting it in sql 2008 using datarow but am getting a error
String was not recognised as valid datetime.
Can any one please help?
DateTime newdate = Convert.ToDateTime(row[8].ToString());
Here how Convert.ToDateTime method looks like when you decompile it;
public static DateTime ToDateTime(string value)
{
if (value == null)
return new DateTime(0L);
else
return DateTime.Parse(value, (IFormatProvider) CultureInfo.CurrentCulture);
}
As you can see, this method use DateTime.Parse method with your CurrentCulture. And if your string doesn't match your current culture date format, your code will be broken. That's the reason you get this error.
Use DateTime.ParseExact with "dd/M/yy hh:mm:ss:tt" format instead.
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.
string s = "23/8/11 01:33:01:PM";
DateTime newdate = DateTime.ParseExact(s, "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
Console.WriteLine(newdate);
Output will be;
8/23/2011 1:33:01 PM
Here a DEMO.
For your case;
DateTime newdate = DateTime.ParseExact(row[8].ToString(), "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
For more informations, take a look;
Custom Date and Time Format Strings
Convert.ToDateTime internally calls DateTime.Parse which by default will use the current culture of your application. If 23/8/11 01:33:01:PM is not a valid format for this culture then this method will fail.
For specific date formats it's best to use DateTime.ParseExact e.g.
DateTime.ParseExact("23/8/11 01:33:01:PM", "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
This approach makes your code culture independent which means the date will always be parsed correctly (given it's in the specified format).
This will work:
DateTime newdate = Convert.ToDateTime("8/23/11 01:33:01 PM");
I changed day and month and removed the colon a the end. But that is very specific. You need to know more about the dates passed to do that.

C# Datetime format conversion

I have a conversion problem with datetime. I have a date string as MM/dd/yyyy. Now I need to convert it to yyyy-MM-dd.
But I'm facing some error. Please help
public static DateTime ToDBDateTime(string _dateTime)
{
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
string _convertedDate = string.Empty;
if (_dateTime != null || _dateTime != string.Empty)
{
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat, System.Globalization.CultureInfo.InvariantCulture).ToString(_toDBDateFormat);
//_convertedDate = Convert.ToDateTime(_dateTime).ToString(_toDBDateFormat);
/// Debug.Print(sysFormat);
}
return Convert.ToDateTime(_convertedDate);
}
And I want to know that is there is any way to pass the datetime in various formats and it would return the expected format.
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
Please provide some suggestion to solve datetime issues.
I have a date string as MM/dd/yyyy
Right... and yet you're trying to parse it like this:
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
...
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat,
CultureInfo.InvariantCulture)
You need to give a format string which matches your input - so why are you including a time part? You probably just want:
string sysFormat = "MM/dd/yyyy";
However, that's not the end of the problems. You're then converting that DateTime back into a string like this:
.ToString(_toDBDateFormat)
... and parsing it once more:
return Convert.ToDateTime(_convertedDate);
Why on earth would you want to do that? You should avoid string conversions as far as possible. Aside from anything else, what's to say that _toDBDateFormat (a variable name which raises my suspicions to start with) and Convert.ToDateTime (which always uses the current culture for parsing) are going to be compatible?
You should:
Work out how you want to handle being given an empty string or null, and just return an appropriate DateTime then
Otherwise, just parse using the right format.
This part of your question also concerns me:
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
There's no such thing as "the date in format as yyyy-MM-dd". A DateTime is just a date and time value. It has no intrinsic format. You specify how you want to format it when you format it. However, if you're using the value for a database query, you shouldn't be converting it into a string again anyway - you should be using parameterized SQL, and just providing it as a DateTime.
As you have a date in a string with the format "MM/dd/yyyy" and want to convert it to "yyyy-MM-dd" you could do like this:
DateTime dt = DateTime.ParseExact(dateString, "MM/dd/yyyy", CultureInfo.InvariantCulture);
dt.ToString("yyyy-MM-dd");
Use the inbuilt tostring like this:
Convert.ToDateTime(_convertedDate).ToString("MM/dd/yyyy") or whatever format you want.
I tried this and its working fine.
DateTime date1 = new DateTime(2009, 8, 1);
date1.ToString("yyyy-MM-dd hh:mm:ss tt");
You can apply any format in this ToString.
Hope that helps
Milind

Get DateTime Obj from "mm/yyyy" format Date string

I have a date string in format "08/1999" I want to get the first date of the corresponding month. eg : in this case 08/01/1999.
It is simple for en-Us culture. I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring) but this is valid for en-US culture only.
How can I do this for different culture ?
My datestring will always be in mm/yyyy format. and I am trying to obtain a DataTime obj from this dateString.
Use ParseExact method. Note upper-cased M's are for months and lower-cased m's for minutes.
string dateToConvert = "08/1999";
string format = "MM/yyyy";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact(dateToConvert, format, provider);
Output:
{1999-08-01 00:00:00}
You can also use Convert.ToDateTime and Parse methods. It will produce the same result, but in implicite way:
DateTime result = Convert.ToDateTime(dateToConvert, provider); // Output: {1999-08-01 00:00:00}
DateTime result = DateTime.Parse(dateToConvert, provider); // Output: {1999-08-01 00:00:00}
Read more at:
Parsing Date and Time Strings
Standard Date and Time Format Strings
Custom Date and Time Format Strings
I'm not sure if I understand your question correctly, but you can try passing CultureInfo.InvariantCulture if you want to force the US date format regardless of the regional settings of the client computer:
DateTime.Parse("08/1999", System.Globalization.CultureInfo.InvariantCulture)
I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring)
That's a very long-winded way to do it. Simply this will work:
DateTime.Parse("08/1999")
How can I do this for different culture ?
If your string is always in this format, do this:
DateTime.Parse("08/1999", CultureInfo.InvariantCulture)

Categories