skip to Main Content

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

5

Answers


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

        DateTime dateTime;
        var from = ""; 
        DateTime.TryParse(from, out dateTime);
    
    Login or Signup to reply.
  2. One-liner, with only the validation you specify:

    StartDTime = from == "" ? new DateTime() : Convert.ToDateTime(from);
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
  4. 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;
    
    Login or Signup to reply.
  5. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search