C# Datetime format conversion - c#

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

Related

DateTime.ParseExact is not doing what i want it to do

When use the .ParseExact() method for the DateTime, i always get the same output as the string i put in. Here is my code:
[Authorize(Roles = "Backoffice, Manager")]
[HttpPost]
public ActionResult FilmShowCreate(FilmShowViewModel newFilmShow)
{
if (ModelState.IsValidField("FilmId") && ModelState.IsValidField("Time"))
{
DateTime unformattedDateTime = newFilmShow.Date.Date + newFilmShow.Time.TimeOfDay;
string dateString = unformattedDateTime.ToString("yyyy-MM-dd HH:mm:ss");
DateTime dbDate = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss",
CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.AdjustToUniversal);
FilmShow filmShow = new FilmShow
{
Film = filmRepository.GetFilm(newFilmShow.FilmId),
Cinema = cinemaRepository.GetCinema(newFilmShow.CinemaId),
ThreeDimensional = newFilmShow.ThreeDimensional,
Date = dbDate,
SpecialEvent = newFilmShow.SpecialEvent
};
filmShowsRepository.AddShow(filmShow);
return View("SuccesfullFilmShowCreate");
The string dateString is formatted good, but it is a string and I need to store it in the database as a format DateTime like this "year-month-day hours:minutes:seconds". But for whatever reason the ParseExact doesn't seem to work in my case. The DateTime format i get is "dd-MM-yyyy HH:mm".
It doesn't do what you want because, well, that function isn't supposed to do what you are describing.
ParseExact simply indicates that the input must match the given format in order to be used (and not throw an exception). It is a counterpart to Parse which will accept any valid Date/Time format. It has absolutely no bearing on the future format of any string representation of the DateTime object it creates.
If you want to output it in a given format, pass your format string into ToString before sending that string to the database. Of course, if you are using something like EF, the conversion is done for you and it shouldn't matter.
Example:
string myFormattedDateTime = dbDate.ToString("yyyy-MM-dd HH:mm:ss");
Reading your question more closely, I realize that you seem to think that DateTime has some "stored" format. It does not. DateTime is just a collection of numbers that hold the information required to represent a date and time. The format you are describing only exists in string representations.

converting a string to a DateTime format

I'm trying to parse 09/01/2015 00:00:00 to the format yyyy-MM-ddThh:mm:ssZ using following method:
DateTime.ParseExact("09/01/2015 00:00:00", "yyyy-MM-ddThh:mm:ssZ", (IFormatProvider)CultureInfo.InvariantCulture);
But I'm getting String was not recognized as a valid DateTime
Can anyone tell me why? I believe 09/01/2015 00:00:00 is a valid DateTime format?
From DateTime.ParseExact
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.
In your case, they are not.
I assume your 09 part is day numbers, you can use dd/MM/yyyy HH:mm:ss format instead.
var dt = DateTime.ParseExact("09/01/2015 00:00:00",
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Since CultureInfo already implements IFormatProvider, you don't need to explicitly cast it.
I don't understand this. So it means I first have to correct my string
and secondly I can do a ParseExact(). I thought ParseExact could
handle the given string...
ParseExact is not a magical method that can parse any formatted string you suplied. It can handle only if your string and format perfectly matches based on culture settings you used.
Try this code:
var text = "09/01/2015 00:00:00";
var format = "dd/MM/yyyy HH:mm:ss";
var dt = DateTime.ParseExact(text, format, (IFormatProvider)CultureInfo.InvariantCulture);
You'll notice that the format must structurally match the text you're trying to parse exactly - hence the ParseExact name for the method.
The format does not match, you need to change 09/01/2015 into 2015-01-09 or theyyyy-MM-dd part into dd/MM/yyyy.
The ParseExact-method is no ultimate method that converts ANY dateformat into another one, it is simply to parse a given string into a datetime using the provided format. Thus if your inout does not match this format the method will throw that exception.
As a datetime is internally only a number there is no need to convert one format into another at all, so as long as you know your input-format you can build a date from it which has nothing to do with any formatting which you may need when you want to print that date to your output. In this case you WILL need a formatter.
As most people have stated the error is coming from the fact that the date in string format doesn't match the format you are saying it's in. You are saying that 09/01/2015 00:00:00 is in the format "yyyy-MM-ddThh:mm:ssZ", which it's not, hence the error. To rectify this you need to either alter the format the string is in, or more likely, change the format you are saying the date is in. So change "yyyy-MM-ddThh:mm:ssZ" to "dd/MM/yyyy HH:mm:ss".
In a more long term view how are you arriving at that date? Is it possible that the format may change (input but the user)? If so it might be better to try and avoid the error being thrown and handle it better with TryParseExact. To make use of this best I generally output a nullable DateTime and then check if it's null. If you don't do this then if the parse fails it will simply make the output datetime the minimum value.
Something like this should work:
public DateTime? StringToDate (string dateString, string dateFormat)
{
DateTime? dt;
DateTime.TryParseExact(dateString, dateFormat, null, System.Globalization.DateTimeStyles.None, out dt);
return dt;
}
Then you can use it like this:
DateTime? MyDateTime = StringToDate("09/01/2015 00:00:00", "dd/MM/yyyy HH:mm:ss");
if(MyDateTime != null)
{
//do something
}
Another simple way to do this...
var dt = Convert.ToDateTime(Convert.ToDateTime("09/01/2015 00:00:00").ToString("yyyy-MM-ddThh:mm:ssZ"))

C# convert DateTime from one format to another

I thought this would be a really simple, and i've tried to google it and I keep getting the exception String was not recognized as a valid DateTime.
This is my value "2013-10-21T14:10:49" this is what I want to convert it into 10/21/2013 10:49
string sample = "2013-10-21T14:10:49";
DateTime date31 = DateTime.ParseExact(sample, "MM/dd/yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture);
When you write DateTime.ParseExact(sample, "MM/dd/yyyy HH:mm", ...), you are saying that sample is in the format MM/dd/yyyy HH:mm. Since it is not, it throws an exception.
It's important to know that a DateTime does not have any format associated with it. It's only when you convert it to or from a string that format can come into play. You should probably use something like this:
string sample = "2013-10-21T14:10:49";
DateTime date31 = DateTime.Parse(sample, System.Globalization.CultureInfo.InvariantCulture);
string date31string = date31.ToString("MM/dd/yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture);
// date31string is "10/21/2013 14:10"
Instead of ParseExact, I used Parse, since the format is recognized by Parse, and I don't see much point in limiting what sort of formats it can accept to only that particular format.
Your string appears to be in format of "Xml-serialized". So it is the job of XmlConvert.
string sample = "2013-10-21T14:10:49";
string converted = XmlConvert.ToDateTime(sample, XmlDateTimeSerializationMode.Unspecified)
.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
You don't need the ParseExact method, the Parse method is sufficient because it allows your date representation. See DateTime - The string to parse for an overview of allowed input formats.
This means the following works:
string sample = "2013-10-21T14:10:49";
DateTime parsed = DateTime.Parse(sample);
Console.WriteLine(parsed.ToString("MM/dd/yyyy HH:mm:ss"));
And the result is:
10/21/2013 14:10:49

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.

Convert YYYYMMDD string to MM/DD/YYYY string

I have a date that is stored as a string in the format YYYYDDMM. I would like to display that value in a 'MM/DD/YYYY' format. I am programming in c#. The current code that I am using is as follows:
txtOC31.Text = dr["OC31"].ToString().Trim();
strOC31date = dr["OC31DATE"].ToString().Trim();
DateTime date31 = DateTime.Parse(strOC31date);
strOC31date = String.Format("{0:MM/dd/yyyy}", date31);
However, I am getting an error because the YYYYMMDD string (strOC31date) is not being recognized as a valid datetime.
DateTime.ParseExact with an example
string res = "20120708";
DateTime d = DateTime.ParseExact(res, "yyyyddMM", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy"));
Use ParseExact() (MSDN) when the string you are trying to parse is not in one of the standard formats. This will allow you to parse a custom format and will be slightly more efficient (I compare them in a blog post here).
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", null);
Passing null for the format provider will default to DateTimeFormatInfo.CurrentInfo and is safe, but you probably want the invariant culture instead:
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
Then your code will work.
Instead of DateTime.Parse(strOC31date); use DateTime.ParseExact() method, which takes format as one of the parameters.
You want the method DateTime.ParseExact.
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyddMM", CultureInfo.InvariantCulture);

Categories