This question already has answers here:
TryParse in if condition
(7 answers)
Closed 9 years ago.
Just a challenge I guess, but I hope to use TryParse in just one line :) My code:
DateTime tempDate;
user.DataNascita = DateTime.TryParse(txtDataDiNascita.Text, out tempDate) ? tempDate : (DateTime?)null;
user.DataNascita is DateTime?, and I want to return the data if TryParse is correct, null otherwise. But I need the out one (so, new line). Can't I have all in one line?
Just curious...
I'm usually using this extension method in LINQ queries:
public static DateTime? TryGetDate(this string dateString, string format = null)
{
DateTime dt;
bool success = format == null ? DateTime.TryParse(dateString, out dt) : DateTime.TryParseExact(dateString, format, null, DateTimeStyles.None, out dt);
return success ? dt : (DateTime?)null;
}
You use it in this way:
user.DataNascita = txtDataDiNascita.Text.TryGetDate();
Here's another overload with multiple formats and an IFormatProvider(different cultures):
public static DateTime? TryGetDate(this string dateString, IFormatProvider provider, params string[] formats)
{
DateTime dt;
var success = DateTime.TryParseExact(dateString, formats, provider, DateTimeStyles.None, out dt);
return success ? dt : (DateTime?)null;
}
You'd need a helper method, basically. For example:
public static DateTime? TryParseDateTime(string text)
{
DateTime validDate;
return DateTime.TryParse(text, out validDate) ? validDate : (DateTime?) null;
}
Then you can just use:
user.DataNascita = ParseHelpers.TryParseDateTime(txtDataDiNascita.Text);
You'd probably want overloads corresponding with the overloads of DateTime.TryParse and DateTime.TryParseExact, too. I wouldn't personally make this an extension method as per Tim's answer, but that's a matter of personal preference.
yea it's easy I didn't find this much of a challenge
DateTime temp; if (DateTime.TryParse(txtDataDiNascita.Text, out temp)) user.DataNascita = temp;
DateTime tempDate; user.DataNascita= DateTime.TryParse(txtDataDiNascita.Text, out tempDate) ? tempDate : (DateTime?)null;
You could do it in a single line as above. but creating your helper method is good approach.
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 want to display a message only when the datetime is before or on todays date. Here is what I have:
var todaysdate = DateTime.Today;
if (acct.maturityDate <= todaysdate )
{
maturityText.Visible = true;
}
I get a message saying that (acct.maturityDate <= todaysdate ).
Cannot apply operator '<=' to operands of type 'string' and 'system.datetime', candidates are bool <=(system.datetime,system.datetime) (in struct datetime).
Any help is appreciated.
As the error says, maturityData is a string and not a DateTime you need to convert it:
var todaysdate = DateTime.Today;
if (DateTime.Parse(acct.maturityDate) <= todaysdate ) {
maturityText.Visible = true;
}
I'm making a direct parse there, you might want to consider TryParse or ParseExact depending on your needs.
This means that the property acct.maturityDate is of the type string and not the expected type System.DateTime. Convert/parse the property to a DateTime and your problem should be solved, or make sure the property is already a DateTime.
As mentioned in my comment, the type of maturityDate is a string. using DateTime.Parse() would allow you to resolve your issues and so will DateTime.TryParseExact()
Converting to the correct type will allow you to use the correct operators.
Firstly you have to change maturityDate to DateTime type, and then you should use DateTime.Compare method you can refer to this link
If maturityDate must be left as-is, you can either use the DateTime.Parse, DateTime.TryParse, or DateTime.TryParseExact methods.
Parse will throw an exception if maturity date cannot be parsed.
TryParse and TryParseExact will not throw exceptions, but will allow you to make a decision based on whether the date is able to be parsed.
TryParseExact allows you to parse your date even if it doesn't match a standard DateTime format. You simply specify the format string, as well as culture and style information, in the method parameters.
Parse Example:
var todaysdate = DateTime.Today;
if (DateTime.Parse(acct.maturityDate) <= todaysdate ) {
maturityText.Visible = true;
}
TryParse Example:
var todaysdate = DateTime.Today;
DateTime dt;
if (DateTime.TryParse(acct.maturityDate, out dt)
{
if (dt <= todaysdate)
{
maturityText.Visible = true;
}
}
TryParseExact Example:
var todaysdate = DateTime.Today;
DateTime dt;
// use whatever format string matches appropriately
if (DateTime.TryParseExact(acct.maturityDate, "YYYY-MM-dd HH:mm:ss"
, CultureInfo.InvariantCulture
, DateTimeStyles.None, out dt)
{
if (dt <= todaysdate)
{
maturityText.Visible = true;
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I use DateTime.TryParse with a Nullable<DateTime>?
I have this line of code
DateTime? dt = Condition == true ? (DateTime?)Convert.ToDateTime(stringDate) : null;
Is this the correct way to convert string to Nullable DateTime, or is there a direct method to convert without converting it to DateTime and again casting it to Nullable DateTime?
You can try this:-
DateTime? dt = string.IsNullOrEmpty(date) ? (DateTime?)null : DateTime.Parse(date);
You are able to build a method to do this:
public static DateTime? TryParse(string stringDate)
{
DateTime date;
return DateTime.TryParse(stringDate, out date) ? date : (DateTime?)null;
}
DateTime? dt = (String.IsNullOrEmpty(stringData) ? (DateTime?)null : DateTime.Parse(dateString));
Simply assigned without cast at all :)
DateTime? dt = Condition == true ? Convert.ToDateTime(stringDate) : null;
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
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I convert a string into datetime in .NET?
I have a string in the following format "15/03/2046". how can convert this string to a DateTime object?
My problem is when I do Convert.ToDateTime("15/03/2046") I get an exception.
when I do Convert.ToDateTime("03/03/2046") every thing works fine.
so I guess that I have to specify the format somehow while converting....
DateTime.Parse or its sister method DateTime.ParseExact.
Use DateTime.ParseExact to specify the format of the input string:
DateTime d = DateTime.ParseExact(
"15/03/2046",
"dd/MM/YYYY",
CultureInfo.InvariantCulture
);
More generic code, using extension method, and default value in case if it can't parse date
void Main()
{
var dt = "15/03/2046";
dt.ToDateTime("fr-FR", DateTime.Now).Dump();
}
public static class Extensions
{
public static DateTime ToDateTime(this string dateTime, string culture, DateTime defaultValue)
{
DateTime dt;
if (DateTime.TryParse(dateTime, System.Globalization.CultureInfo.CreateSpecificCulture(culture), System.Globalization.DateTimeStyles.None, out dt))
return dt;
else
return defaultValue;
}
}