DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);
txtDatumDokum.Text is like "09.09.2011".
but i get FormatException error. Must i parse date?
Try DateTime.ParseExact with the dd.MM.yyyy format string
DateTime.ParseExact(txtDatumDokum.Text, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);
It's not good to see, anyway try this:
string s = "09.09.2011";
DateTime dt = Convert.ToDateTime(
s.Replace(".",
new System.Globalization.DateTimeFormatInfo().DateSeparator));
You need to tell us why the text input is using this format. If it is because the user enters it this way, then you need to make sure that the format matches that given by Thread.CurrentCulture.DateTimeFormat.ShortDatePattern. Changing the culture (by setting
Thread.CurrentCulture) to an appropriate value will then solve your problem.
If you are supposed to parse the input no matter what format it is in, then you will need to do some manual processing first (perhaps remove spaces and other delimiter characters from the input with string.Replace) and then try to parse the date using DateTime.ParseExact and a known format string.
But it all depends on why the input has that format, and why your application's current culture does not match it.
You could try this, TryParse avoids parsing exceptions.. Then you just need check result to be sure that it parsed.
DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, out datuMDokumenta);
You will have to determine if this is a good solution for your application.
See this example:
http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
Judging by the date you gave you need to include a culture, de-DE accepts 01.01.11 type of dates but I'm not sure which one you actually want to use, you'll need to decide that.. the Code would look like this:
using System.Globalization;
DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, CultureInfo.CreateSpecificCulture("de-DE"), DateTimeStyles.None, out datuMDokumenta);
A list of cultures can be found here, select the appropriate one for you:
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.71%29.aspx
The plus here is that this code is a bit more work but it is very difficult to break. Assuming you are using a free text entry on a TextBox you don't want to be throwing exceptions.
Yes you have to parse input date in current culture.
string[] format = new string[] { "dd.MM.yyyy" };
string value = "09.09.2011";
DateTime datetime;
if (DateTime.TryParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out datetime))
//Valid
else
//Invalid
DateTime dt = Convert.ToDateTime(txtDatumDokum.Text)
It is right...there is no isssue
During a Deserialization call under compact framework 3.5 i've had some unexpected behaviour before.
I've converted from using the OpenNETCF serialization classes to the framework XML serialization class. In doing so, the default time format has changed and the order of property/public members. So long story short, i've exposed a text property which converts my date-times back to the format my VB6 application is expecting.
Dim dumbDate As New Date
Dim formats() As String = {"yyyy-MM-ddTHH:mm:ss.fffzzz", _
"yyyy-MM-dd HH:mm:ss:fffffffzzz"}
_datetimeTaken = dumbDate.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)
' There is something wrong with compact framework during the Serialization calls.
' calling the shared method Date.Parse or Date.ParseExact does not produce the same
' result as calling a share method on an instance of Date. WTF?!?!?!
' The below will cause a "Format" exception.
'_datetimeTaken = Date.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)
Date.blah doesn't work. dumbDate.blah works. strange.
public static void Main(string[] args)
{
var dt = new DateTime(2018, 04, 1);
Console.WriteLine(dt);
string month = dt.ToString("MMMM");
Console.WriteLine(month); //April
month = dt.ToString("MMM");
Console.WriteLine(month); //Apr
month = dt.ToString("MM");
Console.WriteLine(month); //04
Console.ReadKey();
}
your code:
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);
try changing this to:
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum);
and when u print the date/time
print datuMDokumenta.Text
Related
I have this code in my controller.this code gives an exception when i'm trying to loop through a DataSet.The exception is given on different rows when i run the project several times.(The exception is not happen at exact row)
The exception is;
String was not recognized as a valid DateTime.
DateTime arrDate = DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString());
i tried this too;
DateTime createdDate = DateTime.ParseExact(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
but it is not working yet..
the value of the row is 2/9/2016 21:20
You just have to cast it to the right type which seems to be DateTime, no need to parse:
DateTime arrDate = ds.Tables[0].Rows[i].Field<DateTime>("CheckInDate");
If it's actually a string(why is that so?) use M/d/yyyy instead of MM/dd/yyyy:
DateTime.ParseExact("2/9/2016 21:20", "M/d/yyyy HH:mm", DateTimeFormatInfo.InvariantInfo);
ParseExact requires that your string exactly matches the pattern you are parsing against.
Your pattern has "MM/dd" which requires double digit months and days ("01/29" or "10/02" or "01/02") but you are only passing in single digit months and days ("2/9").
You either need to change the pattern to accept single digits or change the string to pass double digits.
you need to know in which format the date is retrieved then parse it with the proper format
DateTime dt=DateTime.ParseExact(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
if this format is not apropiate for the current culture (the language and region of the application)
// for example language English and region Canada
DateTime dt=DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), new CultureInfo("en-CA"));
OR
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString()); //uses the current Thread's culture
For more informations, check out Custom Date and Time Format Strings
Try below,
If ( ds.Tables[0].Rows[i]["CheckInDate"] != null ) {
// your code goes here...
DateTime arrDate = DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString());
}
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 get the following error when i try to convert to date time.
String was not recognized as a valid DateTime.
cost.b_date = DateTime.Parse(c_date.Text) ;//c_date.Text = 12/28/2012
Then i try
string date = string.Format("{0:yyyy-MM-dd}",c_date.Text);
cost.b_date = DateTime.Parse(date) ;
but i get the same exception how to fix this problem.
Using string.Format when the input is a string is pointless.
If you know the format of the string, you should use DateTime.ParseExact or DateTime.TryParseExact. For example, for the string you've got, you could use:
DateTime date = DateTime.ParseExact(text, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
You should consider:
Is this user input? If so, use TryParseExact to detect user error more easily without an exception.
Do you definitely know the exact format? If not, using DateTime.TryParse may be more appropriate.
Do you definitely know the culture? If it's not the culture of the current thread, you should specify it explicitly.
Do you have to get the value as text to start with? If you could use an alternative form of input which gives you the value as a DateTime to start with, that would be preferable.
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact(c_date.Text, "d", provider);
Try using DateTime.ParseExact.
DateTime date = DateTime.ParseExact(c_date.Text, "yyyy/MM/dd", null);
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'm trying to convert dates for example 30/12/2000 to 2000-12-30
using this code:
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
DateTime.ParseExact(row.Cells[6].ToString(), "yyyy-MM-dd", enUS);
But I'm getting this error:
String was not recognized as a valid DateTime.
Can someone help me please, Thank you in advance.
You could use DateTime.TryParse() function and check if result is true or false.
So you could try to parse date with a specified format and, if its not right, try another one and so on...
The reason why you are getting this is exactly as the exception says, the string is in an incorrect format, the reason is most likely that the machine doing the comparison has a different date time setting to yyyy-MM-dd.
If you are retrieving this from a database and the return value is of date time (or if you know that row.Cells[6] is a DateTime Field, the following should work:
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
if (row.Cells[6] != null)
DateTime.ParseExact(((DateTime)row.Cells[6]).ToString("yyyy-MM-dd"), "yyyy-MM-dd", enUS);
The question is however why would you want to change the format, to display it on a form if so then you can just display it as follows:
if (row.Cells[6] != null)
TextBox1.Text = ((DateTime)row.Cells[6]).ToString("yyyy-MM-dd");
EDIT
Given that row.Cells[6] is a string, you will always have to know what the format of the string is, and if you do then it would be as simple as:
With time:
DateTime ParsedDate = DateTime.ParseExact(row.Cells[6].ToString(), "dd-MM-yyyy h:mm", enUS);
Removing time and then parsing:
DateTime ParsedDate = DateTime.ParseExact(row.Cells[6].ToString().Substring(0,10), "dd/MM/yyyy", enUS);
and then to output it in the format you want would be as simple as:
TextBox1.Text = ParsedDate.ToString("yyyy-MM-dd");
You are specifying a en-US CultureInfo object, but 30/12/2000 is not a correct US date format
Try this may resolve your issue
String oldScheduledDate = "16-05-2011";
DateFormat oldFormatter = new SimpleDateFormat("dd/MM/yyyy");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
try
{
Date oldDate = (Date)oldFormatter .parse(oldScheduledDate);
}
Catch(Exception ex ) { /// process exception}
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
try {
DateTime.ParseExact(row.Cells[6].ToString(), "yyyy-MM-dd", enUS);
}
catch (FormatException) {
...your code instead of error...
}
I believe that the problem is your second parameter. If you are passing 30/12/200 as your input, it will fail because the second parameter is expecting it separated with dashes.
use
System.Globalization.CultureInfo.InvariantCulture
DateTime.ParseExact(((DateTime)row.Cells[6]).ToString("yyyy-MM-dd"), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)
;
you forgot the hours / minutes:
from the DB it comes like that (converted to string) "12/05/2011 0:00"
DateTime.ParseExact(theCellValue, "MM/dd/yyyy HH:mm", enUS).ToString("yyyy-MM-dd")
creates the string you want, but its totally stupid. you should just make sure that the datetime gets in the first place formatted as you want. (then you never have to parse it)
If your source string is in dd/MM/yyyy, then you shouldn't be using US culture (MM/dd/yyyy) to parse the string.
System.Globalization.CultureInfo enGB = new System.Globalization.CultureInfo("en-GB");
DateTime temp = DateTime.ParseExact(row.Cells[6].Text, "dd/MM/yyyy", enGB);
row.Cells[6] = temp.ToString("yyyy-MM-dd");
Put this in the RowDataBound event of your grid.
I fixed it by using
Convert.ToDateTime(row.Cells[6].Text)
See how simple it is.