Stupid questions but cant get my head around it...
I have a string in this format 20081119
And I have a C# method that converts the string to a DateTime to be entered into a SQL Server DB
public static DateTime MyDateConversion(string dateAsString)
{
return System.DateTime.ParseExact(dateAsString, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
}
The problem is that the Date is coming out like this: Date = 19/11/2008 12:00:00 AM and I need it to be a DateTime of type yyyyMMdd as I am mapping it into a schema to call a stored proc.
Thanks in advance guys.
Cheers,
Con
There is no such thing as "a DateTime of type yyyyMMdd"; a DateTime is just a large integer, indicating the amount of time in an epoch - it doesn't have a format. But that is fine, since you should be using parametrized TSQL anyway - so just add the DateTime as the value of a DbParameter, and it will be handed to the db in an unambiguous way (don't use string concatenation to build a TSQL command):
DbParameter param = cmd.CreateParameter();
param.ParameterName = "#foo";
param.DbType = DbType.DateTime;
param.Value = yourDateTime; // the DateTime returned from .ParseExact
cmd.Parameters.Add(param);
or for a SqlCommand:
cmd.Parameters.Add("#foo", SqlDbType.DateTime).Value = yourDateTime;
If you genuinely need a string, then just use the string directly as a [n][var]char parameter.
Also - in this case, to parse the date I would use the invariant culture (since culture doesn't feature in the format):
DateTime yourDateTime =
DateTime.ParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture);
From the conversation, it seems you might also need to go from a DateTime to a string, in which case simply reverse it:
string dateString = yourDateTime.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
Date Time is a class that, by default, formats it's ToString as 19/11/2008 12:00:00 AM
This is from MSDN which may help you
Because the appearance of date and
time values is dependent on such
factors as culture, international
standards, application requirements,
and personal preference, the DateTime
structure offers a great deal of
flexibility in formatting date and
time values through the overloads of
its ToString method. The default
DateTime.ToString() method returns the
string representation of a date and
time value using the current culture's
short date and long time pattern. The
following example uses the default
DateTime.ToString() method to display
the date and time using the short date
and long time pattern for the en-US
culture, the current culture on the
computer on which the example was run.
You may be able, therefore, to overload the ToString on DateTime to the desired format, else pass the string representation directly to the stored procedure instead
Ok, back to the culture thing... When you say:
the Date is coming out like this: Date
= 19/11/2008 12:00:00 AM
I'm guessing you are running a ToString on the date to see this result? The formatting in ToString will vary based on the culture and will use your current culture by default.
I was able to reproduce the format your are getting by doing this:
var dateString = "20081119";
var fr = new System.Globalization.CultureInfo("fr-FR");
var resultingDate =DateTime.ParseExact(dateString,"yyyyMMdd",System.Globalization.CultureInfo.CurrentCulture);
Console.WriteLine(resultingDate.ToString(fr));
You have a valid date, so the formatting shouldn't matter, but if it does and you need to get it in the format you described, then you need to format it when converting to a string... if it's already a string, then there is no need for the date conversion.
I could be mis-reading your question, but I had to get this out b/c it was bugging me.
I'm thinking it's due to the culture set in CurrentCulture, without knowing what that is, I can't be certain, but specifying en-US works on my end. Here is the code I have:
var dateString = "20081119";
var enUS = new System.Globalization.CultureInfo("en-US");
var resultingDate = DateTime.ParseExact(dateString,"yyyyMMdd",enUS);
Console.WriteLine(resultingDate.ToString());
Give it a try and see if it works for you.
This is what will give exact result you are looking for:
convert( varchar(10), getdate(), 112 ) : datetime to string (YYYYMMDD format)
convert( datetime, '20081203', 112 ) : string to datetime (YYYYMMDD format)
Code side:
DateTimeFormatInfo fmt = (new CultureInfo("hr-HR")).DateTimeFormat;
Console.WriteLine(thisDate.ToString("d", fmt)); // Displays 15.3.2008 (use similar formats acc to your requirements)
or
date1.ToString("YYYYMMDD",CultureInfo.CreateSpecificCulture("en-US"))
date1.ToString("YYYYMMDD");
Details at http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
Related
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"))
I have a string date = 13/07/15 in this format and I want to convert it into DateTime, but I get the error mentioned below
String was not recognized as a valid DateTime.
What can I do to convert into datetime. I have tried this
DateTime dt = Convert.ToDateTime(date);
Never noticed that different cultures write their data and time in different formats? Although the format you use is valid in most Western European countries it is rubbish in the United States.
To overcome this problem, you can ask the system for the current date and time format:
var currentCulture = System.Globalization.CultureInfor.CurrentCulture
IFormatProvider dateTimeFormat = currentCulture.DateTimeFormat;
string dateTxt = #"13/7/2015";
System.DateTime myDate = System.DateTime.Parse(dateTxt, dateTimeFormat);
That should do the trick if your computer has the correct culture.
If you want to be able to understand a lot of cultures, don't ask for the current culture but use one of the constructors of System.Globalization.CultureInfo
Not wise, because does 1/3/2015 mean March 1st, or January 3rd?
Your code DateTime dt = Convert.ToDateTime(date); is perfect. Seems to me like the error is in your database, because it converts it into date if it gets the full year. Please check it in your database.
Do like this,
DateTime date = DateTime.ParseExact(s, "dd/MM/yy", null);
Source : DateTime.ParseExact
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.
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
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)