Hải Trần Thụy
Hải Trần Thụy

Reputation: 39

How to enter datetime variables from keyboard in C#

I need to enter from my keyboard data according to date / month / year format.

I try code like this :

   DateTime dt = new DateTime();
   dt = DateTime.Parse(Console.ReadLine());

But when input date I still enter year first. So how can I fix this. Thanks!

Upvotes: 0

Views: 1863

Answers (4)

Lubens Luma
Lubens Luma

Reputation: 21

To begin, you have to import

using System.Globalization;

  in the header of your code for it to work, after you just put this code

DateTime dt;
dt = DateTime.Parse (Console.ReadLine ());
Console.WriteLine (dt.ToString ("d"
    CultureInfo.CreateSpecificCulture ("NZ-in")));
Console.ReadLine ();

For more information, visit this web page

https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings

Upvotes: 1

ShaneDemskie
ShaneDemskie

Reputation: 388

You can look at a dotnetfiddle of my solution here.

If you look at the DateTime constructor doc, you'll see that the constructor takes in int year, int month, int day in that order, which doesn't match OP's target format. Take a look at my answer for an easy solution.

You can also find the code below:

string targetDateFormat = "dd/MM/yyyy";
DateTime dt;

Console.WriteLine("Enter a date in the format day/month/year");
string enteredDateString = Console.ReadLine();

//This is assuming the string entered is of the correct format, I suggest doing some validation
dt = DateTime.ParseExact(enteredDateString, targetDateFormat,CultureInfo.InvariantCulture);

//This will print in month/day/year format
Console.WriteLine(dt);

//This will print in day/month/year format
Console.WriteLine(dt.ToString("dd/MM/yyyy"));

You'll need to add the following using declarations to your code:

using System.Globalization;

Upvotes: 1

Paul Ferguson
Paul Ferguson

Reputation: 39

Can you show me your Main method in Program.cs? I'm wondering if maybe marking the readline with a verbatim string literal might help. Also you should probably use TryParse so you can handle.

if (!DateTime.TryParse($@"{Console.ReadLine()}", out DateTime result))
{
    throw new FormatException("The Date you entered is not a valid date");
}

Console.WriteLine($"{result.ToString("yyyy/MM/dd")}");

Upvotes: 2

Neil
Neil

Reputation: 11889

Don't forget date formats are different around the world. UK uses day/month/year, US uses month/day/year and China use year/month/day. Beyond that, the separator can also be different (some use slash, some cultures use dash etc).

DateTime.Parse will use the culture that was detected at startup from the O/S. If you want to override this, then you should use DateTime.ParseExact (where you specify the exact pattern), or pass DateTime.Parse the culture you wish to use.

Upvotes: 2

Related Questions