Need to get 2 dates from user input and compare them in an if statement
I am asking the user for an 2 input dates e.g going flight and returning flight then I need to be able to compare in an if statement that if the flights are between the summer range the price is 20% more.
All help appreciated, Visual Studio C#
This is what I tried:
String firstDate;
String secondDate;
double people;
Console.WriteLine("Please Enter the number of people:")
people = Convert.ToDouble(Console.ReadLine());
double flightPrice = 238;
Console.Write("Please enter the arrival date (dd-MM-yyyy):");
firstDate = Console.ReadLine();
Console.Write("Please enter the departure date (dd-MM-yyyy):");
secondDate = Console.ReadLine();
if (firstDate >= "15-06-2018" && secondDate <= "15-08-2018")
{
flightPrice = 238 * 1.20 * people;
}
else
{
flightPrice = 238 * people;
}
Console.ReadLine();
The error is in the if statement (operator >= cannot be applied to operands of type 'string' and 'string'.
c# date datetime int
|
show 2 more comments
I am asking the user for an 2 input dates e.g going flight and returning flight then I need to be able to compare in an if statement that if the flights are between the summer range the price is 20% more.
All help appreciated, Visual Studio C#
This is what I tried:
String firstDate;
String secondDate;
double people;
Console.WriteLine("Please Enter the number of people:")
people = Convert.ToDouble(Console.ReadLine());
double flightPrice = 238;
Console.Write("Please enter the arrival date (dd-MM-yyyy):");
firstDate = Console.ReadLine();
Console.Write("Please enter the departure date (dd-MM-yyyy):");
secondDate = Console.ReadLine();
if (firstDate >= "15-06-2018" && secondDate <= "15-08-2018")
{
flightPrice = 238 * 1.20 * people;
}
else
{
flightPrice = 238 * people;
}
Console.ReadLine();
The error is in the if statement (operator >= cannot be applied to operands of type 'string' and 'string'.
c# date datetime int
1
You tried anything yet? If so how far have you got? Try posting some code to help us understand where you're issue is.
– sr28
Jan 2 at 17:02
2
What API is this for? ASP.NET? WinForms? WPF? UWP?
– Dour High Arch
Jan 2 at 17:03
Sorry im new here, This is a C# homework for school.
– Old Runescape Character
Jan 2 at 17:14
Going to edit the post putting the code I tried.
– Old Runescape Character
Jan 2 at 17:14
Number of people should be int of uint
– ES2018
Jan 2 at 17:51
|
show 2 more comments
I am asking the user for an 2 input dates e.g going flight and returning flight then I need to be able to compare in an if statement that if the flights are between the summer range the price is 20% more.
All help appreciated, Visual Studio C#
This is what I tried:
String firstDate;
String secondDate;
double people;
Console.WriteLine("Please Enter the number of people:")
people = Convert.ToDouble(Console.ReadLine());
double flightPrice = 238;
Console.Write("Please enter the arrival date (dd-MM-yyyy):");
firstDate = Console.ReadLine();
Console.Write("Please enter the departure date (dd-MM-yyyy):");
secondDate = Console.ReadLine();
if (firstDate >= "15-06-2018" && secondDate <= "15-08-2018")
{
flightPrice = 238 * 1.20 * people;
}
else
{
flightPrice = 238 * people;
}
Console.ReadLine();
The error is in the if statement (operator >= cannot be applied to operands of type 'string' and 'string'.
c# date datetime int
I am asking the user for an 2 input dates e.g going flight and returning flight then I need to be able to compare in an if statement that if the flights are between the summer range the price is 20% more.
All help appreciated, Visual Studio C#
This is what I tried:
String firstDate;
String secondDate;
double people;
Console.WriteLine("Please Enter the number of people:")
people = Convert.ToDouble(Console.ReadLine());
double flightPrice = 238;
Console.Write("Please enter the arrival date (dd-MM-yyyy):");
firstDate = Console.ReadLine();
Console.Write("Please enter the departure date (dd-MM-yyyy):");
secondDate = Console.ReadLine();
if (firstDate >= "15-06-2018" && secondDate <= "15-08-2018")
{
flightPrice = 238 * 1.20 * people;
}
else
{
flightPrice = 238 * people;
}
Console.ReadLine();
The error is in the if statement (operator >= cannot be applied to operands of type 'string' and 'string'.
c# date datetime int
c# date datetime int
edited Jan 2 at 17:18
Old Runescape Character
asked Jan 2 at 17:01


Old Runescape CharacterOld Runescape Character
63
63
1
You tried anything yet? If so how far have you got? Try posting some code to help us understand where you're issue is.
– sr28
Jan 2 at 17:02
2
What API is this for? ASP.NET? WinForms? WPF? UWP?
– Dour High Arch
Jan 2 at 17:03
Sorry im new here, This is a C# homework for school.
– Old Runescape Character
Jan 2 at 17:14
Going to edit the post putting the code I tried.
– Old Runescape Character
Jan 2 at 17:14
Number of people should be int of uint
– ES2018
Jan 2 at 17:51
|
show 2 more comments
1
You tried anything yet? If so how far have you got? Try posting some code to help us understand where you're issue is.
– sr28
Jan 2 at 17:02
2
What API is this for? ASP.NET? WinForms? WPF? UWP?
– Dour High Arch
Jan 2 at 17:03
Sorry im new here, This is a C# homework for school.
– Old Runescape Character
Jan 2 at 17:14
Going to edit the post putting the code I tried.
– Old Runescape Character
Jan 2 at 17:14
Number of people should be int of uint
– ES2018
Jan 2 at 17:51
1
1
You tried anything yet? If so how far have you got? Try posting some code to help us understand where you're issue is.
– sr28
Jan 2 at 17:02
You tried anything yet? If so how far have you got? Try posting some code to help us understand where you're issue is.
– sr28
Jan 2 at 17:02
2
2
What API is this for? ASP.NET? WinForms? WPF? UWP?
– Dour High Arch
Jan 2 at 17:03
What API is this for? ASP.NET? WinForms? WPF? UWP?
– Dour High Arch
Jan 2 at 17:03
Sorry im new here, This is a C# homework for school.
– Old Runescape Character
Jan 2 at 17:14
Sorry im new here, This is a C# homework for school.
– Old Runescape Character
Jan 2 at 17:14
Going to edit the post putting the code I tried.
– Old Runescape Character
Jan 2 at 17:14
Going to edit the post putting the code I tried.
– Old Runescape Character
Jan 2 at 17:14
Number of people should be int of uint
– ES2018
Jan 2 at 17:51
Number of people should be int of uint
– ES2018
Jan 2 at 17:51
|
show 2 more comments
3 Answers
3
active
oldest
votes
Try following :
string firstDate = "10-08-2018";
DateTime _firstDate = DateTime.ParseExact(firstDate, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
string secondDate = "10-08-2018";
DateTime _secondDate = DateTime.ParseExact(secondDate, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
if (_firstDate >= DateTime.ParseExact("15-06-2018", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture) &&
_secondDate <= DateTime.ParseExact("15-08-2018", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture))
{
}
Thanks for the reply, but I need the two dates as user input first
– Old Runescape Character
Jan 2 at 17:40
The user inputs are the two strings. I just hard coded values to show all the code needed.
– jdweng
Jan 2 at 17:49
okay ill try it thanks alot
– Old Runescape Character
Jan 2 at 17:57
Thanks it worked!, last thing is there a way to print the number of days in the two dates?
– Old Runescape Character
Jan 2 at 18:07
string totalDays = (_secondDate - _firstDate).TotalDays.ToString();
– jdweng
Jan 2 at 18:30
|
show 4 more comments
If you are expecting the date strings in a specific format, then you can use TryParseExact
method of the DateTime
object to create a DateTime
out of the string, and then use that DateTime
object to do the comparison with your hard-coded dates.
We can also use the similar TryParse
method to get an integer from the user when they enter the number of people. This allows us to give them a message if they enter an incorrect value (like "two"
instead of "2"
) and ask them to try again.
For example:
static void Main()
{
DateTime peakStartDate = new DateTime(2018, 6, 15);
DateTime peakEndDate = new DateTime(2018, 8, 15);
Console.Write("Please Enter the number of people: ");
// Use TryParse to get an integer from the user. If TryParse fails,
// it means they entered an invalid value, so ask them to do it again.
// Otherwise, numPeople will hold the integer value they entered
int numPeople;
while (!int.TryParse(Console.ReadLine(), out numPeople))
{
Console.WriteLine("Error: input was not a whole number.n");
Console.Write("Please Enter the number of people: ");
}
// Now we can set the base flight price for the number of people
double flightPrice = 238 * numPeople;
// Get the arrival date from the user
Console.Write("nPlease enter the arrival date (dd-MM-yyyy): ");
DateTime firstDate;
// If TryParseExact fails, they entered an incorrect format, so we
// keep asking them. If it succeeds, then firstDate will hold the value.
while (!DateTime.TryParseExact(Console.ReadLine(), "dd-MM-yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out firstDate))
{
Console.WriteLine("Error: input was not in correct formatn");
Console.Write("Please enter the arrival date (dd-MM-yyyy): ");
}
// Same process for departure date
Console.Write("nPlease enter the departure date (dd-MM-yyyy):");
DateTime secondDate;
while (!DateTime.TryParseExact(Console.ReadLine(), "dd-MM-yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out secondDate))
{
Console.WriteLine("Error: input was not in correct format");
Console.Write("nPlease enter the departure date (dd-MM-yyyy): ");
}
// If they're travelling during the peak period, increase the price
if (firstDate >= peakStartDate && secondDate <= peakEndDate)
{
flightPrice *= 1.2;
}
Console.ReadLine();
GetKeyFromUser("nDone! Press any key to exit...");
}
If you want to be more flexible and let the user enter single-digit days and/or months, you can create an array of valid formats like so:
string validDateTimeFormats = {"dd-MM-yyyy", "d-MM-yyyy", "dd-M-yyyy", "d-M-yyyy"};
And then pass the array to the TryParseExact
method:
while (!DateTime.TryParseExact(Console.ReadLine(), validDateTimeFormats,
CultureInfo.CurrentCulture, DateTimeStyles.None, out firstDate))
{
Thanks but user jdweng solved it for me!
– Old Runescape Character
Jan 2 at 18:08
Cool. AlthoughParseExact
will throw an exception if the user enters invalid input.TryParseExact
allows you to handle that situation without blowing up... :)
– Rufus L
Jan 2 at 18:09
Alright thanks alot will use it
– Old Runescape Character
Jan 2 at 18:12
add a comment |
You need to cast the date strings to DateTime objects before you can compare them, you cant compare the dates directly as strings.
DateTime arrivalDate = DateTime.Parse(firstDate);
DateTime departureDate = DateTime.Parse(secondDate);
DateTime summerStart = DateTime.Parse("15-06-2018");
DateTime summerEnd = DateTime.Parse("15-08-2018");
if (arrivalDate >= summerStart && departureDate <= summerEnd)
{
flightPrice = 238 * 1.20 * people;
}
else
{
flightPrice = 238 * people;
}
Hey thanks for this but i'm getting an error 'String was not recognized as a valid DateTime. For DateTime = summerStart etc
– Old Runescape Character
Jan 2 at 17:37
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54010299%2fneed-to-get-2-dates-from-user-input-and-compare-them-in-an-if-statement%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Try following :
string firstDate = "10-08-2018";
DateTime _firstDate = DateTime.ParseExact(firstDate, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
string secondDate = "10-08-2018";
DateTime _secondDate = DateTime.ParseExact(secondDate, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
if (_firstDate >= DateTime.ParseExact("15-06-2018", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture) &&
_secondDate <= DateTime.ParseExact("15-08-2018", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture))
{
}
Thanks for the reply, but I need the two dates as user input first
– Old Runescape Character
Jan 2 at 17:40
The user inputs are the two strings. I just hard coded values to show all the code needed.
– jdweng
Jan 2 at 17:49
okay ill try it thanks alot
– Old Runescape Character
Jan 2 at 17:57
Thanks it worked!, last thing is there a way to print the number of days in the two dates?
– Old Runescape Character
Jan 2 at 18:07
string totalDays = (_secondDate - _firstDate).TotalDays.ToString();
– jdweng
Jan 2 at 18:30
|
show 4 more comments
Try following :
string firstDate = "10-08-2018";
DateTime _firstDate = DateTime.ParseExact(firstDate, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
string secondDate = "10-08-2018";
DateTime _secondDate = DateTime.ParseExact(secondDate, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
if (_firstDate >= DateTime.ParseExact("15-06-2018", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture) &&
_secondDate <= DateTime.ParseExact("15-08-2018", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture))
{
}
Thanks for the reply, but I need the two dates as user input first
– Old Runescape Character
Jan 2 at 17:40
The user inputs are the two strings. I just hard coded values to show all the code needed.
– jdweng
Jan 2 at 17:49
okay ill try it thanks alot
– Old Runescape Character
Jan 2 at 17:57
Thanks it worked!, last thing is there a way to print the number of days in the two dates?
– Old Runescape Character
Jan 2 at 18:07
string totalDays = (_secondDate - _firstDate).TotalDays.ToString();
– jdweng
Jan 2 at 18:30
|
show 4 more comments
Try following :
string firstDate = "10-08-2018";
DateTime _firstDate = DateTime.ParseExact(firstDate, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
string secondDate = "10-08-2018";
DateTime _secondDate = DateTime.ParseExact(secondDate, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
if (_firstDate >= DateTime.ParseExact("15-06-2018", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture) &&
_secondDate <= DateTime.ParseExact("15-08-2018", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture))
{
}
Try following :
string firstDate = "10-08-2018";
DateTime _firstDate = DateTime.ParseExact(firstDate, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
string secondDate = "10-08-2018";
DateTime _secondDate = DateTime.ParseExact(secondDate, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
if (_firstDate >= DateTime.ParseExact("15-06-2018", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture) &&
_secondDate <= DateTime.ParseExact("15-08-2018", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture))
{
}
answered Jan 2 at 17:38
jdwengjdweng
17.9k2817
17.9k2817
Thanks for the reply, but I need the two dates as user input first
– Old Runescape Character
Jan 2 at 17:40
The user inputs are the two strings. I just hard coded values to show all the code needed.
– jdweng
Jan 2 at 17:49
okay ill try it thanks alot
– Old Runescape Character
Jan 2 at 17:57
Thanks it worked!, last thing is there a way to print the number of days in the two dates?
– Old Runescape Character
Jan 2 at 18:07
string totalDays = (_secondDate - _firstDate).TotalDays.ToString();
– jdweng
Jan 2 at 18:30
|
show 4 more comments
Thanks for the reply, but I need the two dates as user input first
– Old Runescape Character
Jan 2 at 17:40
The user inputs are the two strings. I just hard coded values to show all the code needed.
– jdweng
Jan 2 at 17:49
okay ill try it thanks alot
– Old Runescape Character
Jan 2 at 17:57
Thanks it worked!, last thing is there a way to print the number of days in the two dates?
– Old Runescape Character
Jan 2 at 18:07
string totalDays = (_secondDate - _firstDate).TotalDays.ToString();
– jdweng
Jan 2 at 18:30
Thanks for the reply, but I need the two dates as user input first
– Old Runescape Character
Jan 2 at 17:40
Thanks for the reply, but I need the two dates as user input first
– Old Runescape Character
Jan 2 at 17:40
The user inputs are the two strings. I just hard coded values to show all the code needed.
– jdweng
Jan 2 at 17:49
The user inputs are the two strings. I just hard coded values to show all the code needed.
– jdweng
Jan 2 at 17:49
okay ill try it thanks alot
– Old Runescape Character
Jan 2 at 17:57
okay ill try it thanks alot
– Old Runescape Character
Jan 2 at 17:57
Thanks it worked!, last thing is there a way to print the number of days in the two dates?
– Old Runescape Character
Jan 2 at 18:07
Thanks it worked!, last thing is there a way to print the number of days in the two dates?
– Old Runescape Character
Jan 2 at 18:07
string totalDays = (_secondDate - _firstDate).TotalDays.ToString();
– jdweng
Jan 2 at 18:30
string totalDays = (_secondDate - _firstDate).TotalDays.ToString();
– jdweng
Jan 2 at 18:30
|
show 4 more comments
If you are expecting the date strings in a specific format, then you can use TryParseExact
method of the DateTime
object to create a DateTime
out of the string, and then use that DateTime
object to do the comparison with your hard-coded dates.
We can also use the similar TryParse
method to get an integer from the user when they enter the number of people. This allows us to give them a message if they enter an incorrect value (like "two"
instead of "2"
) and ask them to try again.
For example:
static void Main()
{
DateTime peakStartDate = new DateTime(2018, 6, 15);
DateTime peakEndDate = new DateTime(2018, 8, 15);
Console.Write("Please Enter the number of people: ");
// Use TryParse to get an integer from the user. If TryParse fails,
// it means they entered an invalid value, so ask them to do it again.
// Otherwise, numPeople will hold the integer value they entered
int numPeople;
while (!int.TryParse(Console.ReadLine(), out numPeople))
{
Console.WriteLine("Error: input was not a whole number.n");
Console.Write("Please Enter the number of people: ");
}
// Now we can set the base flight price for the number of people
double flightPrice = 238 * numPeople;
// Get the arrival date from the user
Console.Write("nPlease enter the arrival date (dd-MM-yyyy): ");
DateTime firstDate;
// If TryParseExact fails, they entered an incorrect format, so we
// keep asking them. If it succeeds, then firstDate will hold the value.
while (!DateTime.TryParseExact(Console.ReadLine(), "dd-MM-yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out firstDate))
{
Console.WriteLine("Error: input was not in correct formatn");
Console.Write("Please enter the arrival date (dd-MM-yyyy): ");
}
// Same process for departure date
Console.Write("nPlease enter the departure date (dd-MM-yyyy):");
DateTime secondDate;
while (!DateTime.TryParseExact(Console.ReadLine(), "dd-MM-yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out secondDate))
{
Console.WriteLine("Error: input was not in correct format");
Console.Write("nPlease enter the departure date (dd-MM-yyyy): ");
}
// If they're travelling during the peak period, increase the price
if (firstDate >= peakStartDate && secondDate <= peakEndDate)
{
flightPrice *= 1.2;
}
Console.ReadLine();
GetKeyFromUser("nDone! Press any key to exit...");
}
If you want to be more flexible and let the user enter single-digit days and/or months, you can create an array of valid formats like so:
string validDateTimeFormats = {"dd-MM-yyyy", "d-MM-yyyy", "dd-M-yyyy", "d-M-yyyy"};
And then pass the array to the TryParseExact
method:
while (!DateTime.TryParseExact(Console.ReadLine(), validDateTimeFormats,
CultureInfo.CurrentCulture, DateTimeStyles.None, out firstDate))
{
Thanks but user jdweng solved it for me!
– Old Runescape Character
Jan 2 at 18:08
Cool. AlthoughParseExact
will throw an exception if the user enters invalid input.TryParseExact
allows you to handle that situation without blowing up... :)
– Rufus L
Jan 2 at 18:09
Alright thanks alot will use it
– Old Runescape Character
Jan 2 at 18:12
add a comment |
If you are expecting the date strings in a specific format, then you can use TryParseExact
method of the DateTime
object to create a DateTime
out of the string, and then use that DateTime
object to do the comparison with your hard-coded dates.
We can also use the similar TryParse
method to get an integer from the user when they enter the number of people. This allows us to give them a message if they enter an incorrect value (like "two"
instead of "2"
) and ask them to try again.
For example:
static void Main()
{
DateTime peakStartDate = new DateTime(2018, 6, 15);
DateTime peakEndDate = new DateTime(2018, 8, 15);
Console.Write("Please Enter the number of people: ");
// Use TryParse to get an integer from the user. If TryParse fails,
// it means they entered an invalid value, so ask them to do it again.
// Otherwise, numPeople will hold the integer value they entered
int numPeople;
while (!int.TryParse(Console.ReadLine(), out numPeople))
{
Console.WriteLine("Error: input was not a whole number.n");
Console.Write("Please Enter the number of people: ");
}
// Now we can set the base flight price for the number of people
double flightPrice = 238 * numPeople;
// Get the arrival date from the user
Console.Write("nPlease enter the arrival date (dd-MM-yyyy): ");
DateTime firstDate;
// If TryParseExact fails, they entered an incorrect format, so we
// keep asking them. If it succeeds, then firstDate will hold the value.
while (!DateTime.TryParseExact(Console.ReadLine(), "dd-MM-yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out firstDate))
{
Console.WriteLine("Error: input was not in correct formatn");
Console.Write("Please enter the arrival date (dd-MM-yyyy): ");
}
// Same process for departure date
Console.Write("nPlease enter the departure date (dd-MM-yyyy):");
DateTime secondDate;
while (!DateTime.TryParseExact(Console.ReadLine(), "dd-MM-yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out secondDate))
{
Console.WriteLine("Error: input was not in correct format");
Console.Write("nPlease enter the departure date (dd-MM-yyyy): ");
}
// If they're travelling during the peak period, increase the price
if (firstDate >= peakStartDate && secondDate <= peakEndDate)
{
flightPrice *= 1.2;
}
Console.ReadLine();
GetKeyFromUser("nDone! Press any key to exit...");
}
If you want to be more flexible and let the user enter single-digit days and/or months, you can create an array of valid formats like so:
string validDateTimeFormats = {"dd-MM-yyyy", "d-MM-yyyy", "dd-M-yyyy", "d-M-yyyy"};
And then pass the array to the TryParseExact
method:
while (!DateTime.TryParseExact(Console.ReadLine(), validDateTimeFormats,
CultureInfo.CurrentCulture, DateTimeStyles.None, out firstDate))
{
Thanks but user jdweng solved it for me!
– Old Runescape Character
Jan 2 at 18:08
Cool. AlthoughParseExact
will throw an exception if the user enters invalid input.TryParseExact
allows you to handle that situation without blowing up... :)
– Rufus L
Jan 2 at 18:09
Alright thanks alot will use it
– Old Runescape Character
Jan 2 at 18:12
add a comment |
If you are expecting the date strings in a specific format, then you can use TryParseExact
method of the DateTime
object to create a DateTime
out of the string, and then use that DateTime
object to do the comparison with your hard-coded dates.
We can also use the similar TryParse
method to get an integer from the user when they enter the number of people. This allows us to give them a message if they enter an incorrect value (like "two"
instead of "2"
) and ask them to try again.
For example:
static void Main()
{
DateTime peakStartDate = new DateTime(2018, 6, 15);
DateTime peakEndDate = new DateTime(2018, 8, 15);
Console.Write("Please Enter the number of people: ");
// Use TryParse to get an integer from the user. If TryParse fails,
// it means they entered an invalid value, so ask them to do it again.
// Otherwise, numPeople will hold the integer value they entered
int numPeople;
while (!int.TryParse(Console.ReadLine(), out numPeople))
{
Console.WriteLine("Error: input was not a whole number.n");
Console.Write("Please Enter the number of people: ");
}
// Now we can set the base flight price for the number of people
double flightPrice = 238 * numPeople;
// Get the arrival date from the user
Console.Write("nPlease enter the arrival date (dd-MM-yyyy): ");
DateTime firstDate;
// If TryParseExact fails, they entered an incorrect format, so we
// keep asking them. If it succeeds, then firstDate will hold the value.
while (!DateTime.TryParseExact(Console.ReadLine(), "dd-MM-yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out firstDate))
{
Console.WriteLine("Error: input was not in correct formatn");
Console.Write("Please enter the arrival date (dd-MM-yyyy): ");
}
// Same process for departure date
Console.Write("nPlease enter the departure date (dd-MM-yyyy):");
DateTime secondDate;
while (!DateTime.TryParseExact(Console.ReadLine(), "dd-MM-yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out secondDate))
{
Console.WriteLine("Error: input was not in correct format");
Console.Write("nPlease enter the departure date (dd-MM-yyyy): ");
}
// If they're travelling during the peak period, increase the price
if (firstDate >= peakStartDate && secondDate <= peakEndDate)
{
flightPrice *= 1.2;
}
Console.ReadLine();
GetKeyFromUser("nDone! Press any key to exit...");
}
If you want to be more flexible and let the user enter single-digit days and/or months, you can create an array of valid formats like so:
string validDateTimeFormats = {"dd-MM-yyyy", "d-MM-yyyy", "dd-M-yyyy", "d-M-yyyy"};
And then pass the array to the TryParseExact
method:
while (!DateTime.TryParseExact(Console.ReadLine(), validDateTimeFormats,
CultureInfo.CurrentCulture, DateTimeStyles.None, out firstDate))
{
If you are expecting the date strings in a specific format, then you can use TryParseExact
method of the DateTime
object to create a DateTime
out of the string, and then use that DateTime
object to do the comparison with your hard-coded dates.
We can also use the similar TryParse
method to get an integer from the user when they enter the number of people. This allows us to give them a message if they enter an incorrect value (like "two"
instead of "2"
) and ask them to try again.
For example:
static void Main()
{
DateTime peakStartDate = new DateTime(2018, 6, 15);
DateTime peakEndDate = new DateTime(2018, 8, 15);
Console.Write("Please Enter the number of people: ");
// Use TryParse to get an integer from the user. If TryParse fails,
// it means they entered an invalid value, so ask them to do it again.
// Otherwise, numPeople will hold the integer value they entered
int numPeople;
while (!int.TryParse(Console.ReadLine(), out numPeople))
{
Console.WriteLine("Error: input was not a whole number.n");
Console.Write("Please Enter the number of people: ");
}
// Now we can set the base flight price for the number of people
double flightPrice = 238 * numPeople;
// Get the arrival date from the user
Console.Write("nPlease enter the arrival date (dd-MM-yyyy): ");
DateTime firstDate;
// If TryParseExact fails, they entered an incorrect format, so we
// keep asking them. If it succeeds, then firstDate will hold the value.
while (!DateTime.TryParseExact(Console.ReadLine(), "dd-MM-yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out firstDate))
{
Console.WriteLine("Error: input was not in correct formatn");
Console.Write("Please enter the arrival date (dd-MM-yyyy): ");
}
// Same process for departure date
Console.Write("nPlease enter the departure date (dd-MM-yyyy):");
DateTime secondDate;
while (!DateTime.TryParseExact(Console.ReadLine(), "dd-MM-yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out secondDate))
{
Console.WriteLine("Error: input was not in correct format");
Console.Write("nPlease enter the departure date (dd-MM-yyyy): ");
}
// If they're travelling during the peak period, increase the price
if (firstDate >= peakStartDate && secondDate <= peakEndDate)
{
flightPrice *= 1.2;
}
Console.ReadLine();
GetKeyFromUser("nDone! Press any key to exit...");
}
If you want to be more flexible and let the user enter single-digit days and/or months, you can create an array of valid formats like so:
string validDateTimeFormats = {"dd-MM-yyyy", "d-MM-yyyy", "dd-M-yyyy", "d-M-yyyy"};
And then pass the array to the TryParseExact
method:
while (!DateTime.TryParseExact(Console.ReadLine(), validDateTimeFormats,
CultureInfo.CurrentCulture, DateTimeStyles.None, out firstDate))
{
edited Jan 2 at 18:08
answered Jan 2 at 18:05


Rufus LRufus L
19.3k31732
19.3k31732
Thanks but user jdweng solved it for me!
– Old Runescape Character
Jan 2 at 18:08
Cool. AlthoughParseExact
will throw an exception if the user enters invalid input.TryParseExact
allows you to handle that situation without blowing up... :)
– Rufus L
Jan 2 at 18:09
Alright thanks alot will use it
– Old Runescape Character
Jan 2 at 18:12
add a comment |
Thanks but user jdweng solved it for me!
– Old Runescape Character
Jan 2 at 18:08
Cool. AlthoughParseExact
will throw an exception if the user enters invalid input.TryParseExact
allows you to handle that situation without blowing up... :)
– Rufus L
Jan 2 at 18:09
Alright thanks alot will use it
– Old Runescape Character
Jan 2 at 18:12
Thanks but user jdweng solved it for me!
– Old Runescape Character
Jan 2 at 18:08
Thanks but user jdweng solved it for me!
– Old Runescape Character
Jan 2 at 18:08
Cool. Although
ParseExact
will throw an exception if the user enters invalid input. TryParseExact
allows you to handle that situation without blowing up... :)– Rufus L
Jan 2 at 18:09
Cool. Although
ParseExact
will throw an exception if the user enters invalid input. TryParseExact
allows you to handle that situation without blowing up... :)– Rufus L
Jan 2 at 18:09
Alright thanks alot will use it
– Old Runescape Character
Jan 2 at 18:12
Alright thanks alot will use it
– Old Runescape Character
Jan 2 at 18:12
add a comment |
You need to cast the date strings to DateTime objects before you can compare them, you cant compare the dates directly as strings.
DateTime arrivalDate = DateTime.Parse(firstDate);
DateTime departureDate = DateTime.Parse(secondDate);
DateTime summerStart = DateTime.Parse("15-06-2018");
DateTime summerEnd = DateTime.Parse("15-08-2018");
if (arrivalDate >= summerStart && departureDate <= summerEnd)
{
flightPrice = 238 * 1.20 * people;
}
else
{
flightPrice = 238 * people;
}
Hey thanks for this but i'm getting an error 'String was not recognized as a valid DateTime. For DateTime = summerStart etc
– Old Runescape Character
Jan 2 at 17:37
add a comment |
You need to cast the date strings to DateTime objects before you can compare them, you cant compare the dates directly as strings.
DateTime arrivalDate = DateTime.Parse(firstDate);
DateTime departureDate = DateTime.Parse(secondDate);
DateTime summerStart = DateTime.Parse("15-06-2018");
DateTime summerEnd = DateTime.Parse("15-08-2018");
if (arrivalDate >= summerStart && departureDate <= summerEnd)
{
flightPrice = 238 * 1.20 * people;
}
else
{
flightPrice = 238 * people;
}
Hey thanks for this but i'm getting an error 'String was not recognized as a valid DateTime. For DateTime = summerStart etc
– Old Runescape Character
Jan 2 at 17:37
add a comment |
You need to cast the date strings to DateTime objects before you can compare them, you cant compare the dates directly as strings.
DateTime arrivalDate = DateTime.Parse(firstDate);
DateTime departureDate = DateTime.Parse(secondDate);
DateTime summerStart = DateTime.Parse("15-06-2018");
DateTime summerEnd = DateTime.Parse("15-08-2018");
if (arrivalDate >= summerStart && departureDate <= summerEnd)
{
flightPrice = 238 * 1.20 * people;
}
else
{
flightPrice = 238 * people;
}
You need to cast the date strings to DateTime objects before you can compare them, you cant compare the dates directly as strings.
DateTime arrivalDate = DateTime.Parse(firstDate);
DateTime departureDate = DateTime.Parse(secondDate);
DateTime summerStart = DateTime.Parse("15-06-2018");
DateTime summerEnd = DateTime.Parse("15-08-2018");
if (arrivalDate >= summerStart && departureDate <= summerEnd)
{
flightPrice = 238 * 1.20 * people;
}
else
{
flightPrice = 238 * people;
}
answered Jan 2 at 17:32
ShwabsterShwabster
3241922
3241922
Hey thanks for this but i'm getting an error 'String was not recognized as a valid DateTime. For DateTime = summerStart etc
– Old Runescape Character
Jan 2 at 17:37
add a comment |
Hey thanks for this but i'm getting an error 'String was not recognized as a valid DateTime. For DateTime = summerStart etc
– Old Runescape Character
Jan 2 at 17:37
Hey thanks for this but i'm getting an error 'String was not recognized as a valid DateTime. For DateTime = summerStart etc
– Old Runescape Character
Jan 2 at 17:37
Hey thanks for this but i'm getting an error 'String was not recognized as a valid DateTime. For DateTime = summerStart etc
– Old Runescape Character
Jan 2 at 17:37
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54010299%2fneed-to-get-2-dates-from-user-input-and-compare-them-in-an-if-statement%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
You tried anything yet? If so how far have you got? Try posting some code to help us understand where you're issue is.
– sr28
Jan 2 at 17:02
2
What API is this for? ASP.NET? WinForms? WPF? UWP?
– Dour High Arch
Jan 2 at 17:03
Sorry im new here, This is a C# homework for school.
– Old Runescape Character
Jan 2 at 17:14
Going to edit the post putting the code I tried.
– Old Runescape Character
Jan 2 at 17:14
Number of people should be int of uint
– ES2018
Jan 2 at 17:51