When try to convert string value in date-time format some time string variable comes with null value at that time it throws exception invalid format of the sting.
e.g
string abc=//date vale
datetime dt=new datetime();
dt=DateTime.Parse(abc);
//if abc comes null it throws exception.
//I can check in this way
if(abc!=null)
{
dt=DateTime.Parse(abc);
}
Have a look at DateTime.TryParse[MSDN].
EDIT:
If you don't want to duplicate this code, put it in a method, perhaps with a nullable return value:
public DateTime? ParseDate(string dateString)
{
DateTime dt;
if (DateTime.TryParse(dateString, out dt))
{
return dt;
}
else
{
return null;
}
}
Use the following code.
string abc=//date vale
DateTime dt;
if(DateTime.TryParse(abc, out dt)
{
// do something
}
You can use DateTime.TryParse(string s, out DateTime result). This method will try to parse the string into the result and return true if it worked / false if parsing isn't possible.
string abc = //date vale
datetime dt;
bool didItWork = DateTime.TryParse(abc, out dt);
You should be using DateTime.TryParse() to make sure you avoid the exception.
use this one
Convert.ToDateTime();
and check this link
http://msdn.microsoft.com/en-us/library/9xk1h71t.aspx
Related
I am trying to convert a datatime string "including milliseconds" into a DataTime. I tried tried to use DateTime.TryParseExact but it does not give me a milliseconds.
Here is what I have tired
public static DateTime? dateTimeVal(string raw, string format = null)
{
DateTime final;
if(raw != null){
if( format != null){
string[] formats = new[] { format };
if (DateTime.TryParseExact(raw, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out final))
{
return final;
}
}
if (DateTime.TryParse(raw, out final))
{
return final;
}
}
return null;
}
This is how I use the method above
DateTime? dt = dateTimeVal("2016-03-14 11:22:21.352", "yyyy-MM-dd HH:mm:ss.fff");
However, dt gives me this 3/14/2016 11:22:21 AM
How can I get the value to include the milliseconds?
DateTime final = new DateTime();
var test = DateTime.TryParseExact("2016-03-14 11:22:21.352", new string[] { "yyyy-MM-dd HH:mm:ss.fff" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out final);
This works for me.
Just take care for your fff. If you write them uppercase, the milliseconds will be supressed. Lowercase they will be parsed.
The only thing away from that I can imagine is you have used .ToString without providing any format. Then you'll get:
Are you sure you've written the providing format lowercase inside your code? Also have you used .ToString() with an output-format that shows up the milliseconds?
If you want to get the DateTime as string with milisecond, then you can use the following code;
string dateTime = dt.Value.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
Hope this helps.
I am writing a Converter for my DatePicker, which is bound to a field within a table. Everything appears to be working fine, except that if the user wipes the date. It then displays (and potentially stores) the date as 01/01/0001, where as I really do need it to be a blank/null value.
Can someone tell me what I am doing wrong.
try
{
DateTime dt;
string strValue = value.ToString();
if (DateTime.TryParseExact(strValue, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
return dt.ToString("yyyy-MM-dd");
}
else
{
return null;
}
}
catch (Exception ex)
{
return null;
}
Unfortunately, DateTime is a Struct i.e. a value type which cannot be null.
However you can do inside if statement after you parse it
if (dt == DateTime.MinValue)
return String.Empty;
else
return dt.ToString("yyyy-MM-dd");
DateTime is a value type and cannot be null.
If you want "null" DateTime values, then simply use a nullable DateTime.
DateTime? MyDate { get; set; }
You can use a Nullable datetime by doing this:
public DateTime? YourDate { get; set; }
This is an extremely common problem and has a number of potential solutions. The first is to use the nullable DateTime struct:
DateTime? nullableDateTime = null;
Another solution is just to edit the date value before it goes to the database and once it comes out of the database:
Into the database:
if (yourDateValue == DateTime.MinValue) databaseTable.Date = null;
else databaseTable.Date = yourDateValue;
Out of the database:
if (databaseTable.Date == null) yourDateValue = DateTime.MinValue;
else yourDateValue = databaseTable.Date;
I have a function that checks for null values then converts dates if they are not null
the below function just had "08/09/13" sent to it (English format) and i got "String was not recognized as a valid DateTime."
anyone help me as to why? do i need to tell the something somewhere is uses English format?
Thanks
public static DateTime DateTimeCheck(object objDateTime)
{
if (objDateTime == null || objDateTime == "")
return default(DateTime);
return Convert.ToDateTime(objDateTime);
}
I don't understand why you passed an object as a parameter instead of string first of all.
Try this instead;
public static DateTime DateTimeCheck(object objDateTime)
{
...
return DateTime.ParseExact(objDateTime.ToString(),"dd/MM/yy",CultureInfo.InvariantCulture);
}
Of course, this throws exception if your object is not formatted same as with "dd/MM/yy".
Take a look at;
Custom Date and Time Format Strings
You can use the overloaded method that accepts the culture information:
Convert.ToDateTime(o, new CultureInfo("en-Gb"));
To get or set the current culture you can use:
System.Threading.Thread.CurrentThread.CurrentCulture
You might be in a different culture with a different default date format. However you can use ParseExact to parse in the expected format. For example:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact("25/12/82","dd/MM/yy",provider);
I know this not what you are looking for but that's how to be sure that some object has date time value in it something like that :
public static DateTime DateTimeCheck(object objDateTime)
{
DateTime dateTime ;
if (objDateTime != null)
{
if (DateTime.TryParse(objDateTime.ToString(), out dateTime))
{
return Convert.ToDateTime(objDateTime);
}
}
return default(DateTime);
}
Try this:
DateTime.ParseExact((string)objDateTime,"dd/MM/yyyy",CultureInfo.InvariantCulture);
I have the following method in order to verify whether a string is a valid datetime:
public bool isDate(string date)
{
bool check = false;
try
{
DateTime converted_date = Convert.ToDateTime(date);
check = true;
}
catch (Exception)
{
check = false;
}
return check;
}
Now, the exception "String was not recognized as valid datetime" is caught whenever I try to pass a string like this:
"12/31/2013 12:00:00 AM"
I cannot understand why this is happening. Can someone help me solve this please?
Instead of the try/catch block, try the built in TryParse method in the DateTime class. It takes your string as a parameter and if it converts successfully it will place the value in the "result" variable. It returns a boolean value representing whether it worked or not.
public bool isDate(string date)
{
var result = new DateTime();
return DateTime.TryParse(date, out result);
}
Most likely your current culture settings are different from the format date is provided in. You can try specifying the culture explicitly:
CultureInfo culture = new CultureInfo("en-US"); // or whatever culture you want
Convert.ToDateTime(date, culture);
You can also use DateTime.TryParseExact and pass a format string (eg. MM/dd/yy H:mm:ss zzz, see more here) to check if the date has a specific format.
I want to add a date in session (date1) like this:
Session["DateLesson"] = date1.ToString("dd.MM.yyyy");
Now from the session I want take this value:
var asd = Session["DateLesson"];
/*asd = "20.04.2012"*/
var datelesson = DateTime.Parse((string) asd);
And it gives me this exception:
FormatException not recognized as a valid DateTime
A period is not a valid/standard separator character in most locales. You'll need to use DateTime.ParseExact() in combination with a format string to tell the function how to read it. More importantly, if reading it back to a datetime is your main goal, why not just put the datetime in the session as is? That seems way more efficient, easier, and more maintainable to me.
Why persist your date as a string?
You could simply store it like this:
Session["DateLesson"] = date1;
And then retrieve it like this:
var datelesson = (DateTime)Session["DateLesson"];
string value = "20.04.2012";
DateTime datetime = DateTime.ParseExact(value, "dd.MM.yyyy", null);
This will return 4/20/2012 12:00:00:00 AM
Don't keep value as a string but as an object of the initial type:
public DateTime? DateLesson
{
get
{
DateTime? dateTime = Session["DateLesson"] as DateTime?;
if (dateTime.HasValue) // not null
{
// use dateTime.Value
}
}
set
{
Session["DateLesson"] = value;
}
}