Shutere
Shutere

Reputation: 1

C# - How do I get a user input for date and time

I want to be able to get a point from a database using the date and time the point was created. I want to do this by asking the user what date/time they want and then use that date/time to find the point. This is my code currently, it gets the point but only the data from the exact time I run the code. I would like to be able to get data from a 6/4/2012 4:50:29 for example.

//connect to pi server
    PIServers piServers = new PIServers();
         foreach (var server in piServers)
         {
             Console.WriteLine("Server: {0}", server.Name);
         }
         PIServer piServer = piServers.DefaultPIServer;
         Console.WriteLine("Default Server: {0}", piServer.Name);

        piServer.Connect();

        //get a PI Point
        var point = PIPoint.FindPIPoint(piServer, "Pipoint");

        var value = point.Snapshot();
        Console.WriteLine("Point {0} Value {1} {2}", point.Name,
        value.Value.ToString(),value.Timestamp.ToString());

Thank you very much for the help.

Upvotes: 0

Views: 16994

Answers (2)

Ju66ernaut
Ju66ernaut

Reputation: 2691

You have to get an input from a user and store that value in a variable.

I am assuming var point = PIPoint.FindPIPoint(piServer, "Pipoint"); is the line of code that queries the DB for a match.

In that case you would want to pass the datetime as a string. string input = Console.Readline(); and then just pass userInput to the FindPIPoint method.

But if the .FindPiPoint method is looking for a datetime you would need to cast it to a datetime object first.

Since this is working on the assumption that any possible datetime is a possible match(and I doubt this is the case) you should add some error handling for an incorrect match.

Upvotes: 0

Jamie Rees
Jamie Rees

Reputation: 8183

What you need to do is first ask the user:

Console.WriteLine("Enter date");
var userInput = Console.ReadLine();

Now userInput is a string so you need to cast it into a DateTime object, I would not cast it directly since it is very easy to get a InvalidCastException, so we should use the built in TryParse(String, out DateTime) to validate if it is a correct DateTime.

DateTime result;
DateTime.TryParse(userInput, out result);

If userInput was a correct DateTime then the result will be a valid DateTime object. If it was not correct the result will be DateTime.MinValue so I would check:

if(!result.Equals(DateTime.MinValue))
{
  // Continue to look it up in the DB
}

Upvotes: 2

Related Questions