Home > Mobile >  C# DateTime and String value condition check
C# DateTime and String value condition check

Time:10-27

I have a problem.

This is not working

> var from = "";
> StartDTime = Convert.ToDateTime(from);

This is working

> var from = "2021-10-05";
> StartDTime = Convert.ToDateTime(from);

Some time I'm sending Date Value, but sometime in not sending Date Value.in that time from variable pass as a empty string. I want to set if from variable is = "" then need to set default Date Value.so how can I resolve this?. Please help me guys. Thank you

CodePudding user response:

DateTime.TryParse will do the job for you: for example:

    DateTime dateTime;
    var from = ""; 
    DateTime.TryParse(from, out dateTime);

CodePudding user response:

A safe way of doing that would be:

StartDTime = string.IsNullOrEmpty(from) ? DateTime.Now : DateTime.Parse(from);

But if you have control over the code passing the "from" variable, you can declare it as nullable DateTime, then your code would look like this:

DateTime? from = null;
var StartDTime = from.HasValue ? from.Value : DateTime.Now;

Which for short would be:

StartDTime = from ?? DateTime.Now;

CodePudding user response:

One-liner, with only the validation you specify:

StartDTime = from == "" ? new DateTime() : Convert.ToDateTime(from);

CodePudding user response:

It's not ellegant, but works.

var from = "";
if(from == ""){ from = DateTime.MinValue.ToString(); }
DateTime StartDTime = Convert.ToDateTime(from);

But i think that a nullable DateTime would be more elegant, like this:

var from = null;
DateTime? StartDTime = from;

Or you can set a default date, like this:

var from = null;
DateTime? StartDTime = from ?? YourDefaultDate;

CodePudding user response:

Convert methods either successfully convert the string passed to it, or throws an error, that's the way it's supposed to work. For most data types there are also TryParse methods that return true/false based on if it converted successfully and have an output variable which will be DateTime.MinValue if it failed. This is how I would handle your situation:

DateTime startDTime;
string from = "";
if (!DateTime.TryParse(from, out startDTime)){
    startDTime = DateTime.Now;
}

This will set the startTime to the date passed in from, but if no date was passed it sets it to the current date and time - if you want a different default value, that replaces new DateTime() and if your default should be January 1, 0001, then you can just use the TryParse part directly, since that's the automatic default for a failed TryParse.

CodePudding user response:

You can use DateTime.TryParse() instead of Convert.ToDateTime() like this:

var from = ""
var date = DateTime.Now; // This is your default value
DateTime.TryParse( from,  out date );
Console.WriteLn(date);
  • Related