Determining how long a trip takes in minutes - c#

Have the user enter an arrival time such in the format 3:30 PM
Then ask the user how long it takes to get to their destination.
I then need to display the time they need to leave in order to arrive to their destination on time.
I have this so far
Console.WriteLine("Enter the arrival time <e.g. 3:30 PM>:");
DateTime time = Convert.ToDateTime(Console.ReadLine());
Console.WriteLine("How long is the trip time in minutes:");
string date = Console.ReadLine();
DateTime durationOfTrip = DateTime.Parse(date);
TimeSpan diff = time.Subtract(durationOfTrip);
Console.WriteLine(diff);
Console.ReadLine();
I get this error
An unhandled exception of type System.FormatException occurred in mscorlib.dll
Additional information: String was not recognized as a valid DateTime.

I suspect you're trying to parse the string "3:30 PM" into an instance of DateTime. You'll need to use a custom parse string:
string arrivalInput = Console.ReadLine();
var arrival =
DateTime.ParseExact(
arrivalTimeInput,
"hh:mm tt",
CultureInfo.InvariantCulture
);
This will parse the time, but it will set the date component to today.
Unfortunately, there is just no clean encapsulation of time only in the framework.
Then your next problem is
string date = Console.ReadLine();
DateTime durationOfTrip = DateTime.Parse(date);
where you're trying to parse something like "30" into a DateTime. That's clearly not going to fly. You told the user to enter the input in minutes, so convert the input to an instance of TimeSpan:
string durationInput = Console.ReadLine();
var duration = new TimeSpan(0, Int32.Parse(durationInput), 0);
or
var duration = TimeSpan.ParseExact(s, "mm", CultureInfo.InvariantCulture);
Then, what you need to do is subtract duration from arrival, this will give you a new instance of DateTime, and then you need to use an appropriate format string to only output the time.
Note that I've given your variable names slightly more meaningful names. The name date for the user input trip duration was particularly unclear.

An average user would enter an integer number ("time in minutes"), and you're trying to parse this into a DateTime structure. How would .NET know what these numbers mean? They might as well be milliseconds.
The first step would probably be parsing the input to an int, and then using the AddMinutes() method JMK mentioned to apply the minutes to the already created DateTime time.

Related

Parse date string with single digit day e.g. 1-11-2017 as well as 12-11-2017

So I have a date String coming in with the short date of today.
For Example "1-11-2017"
//Here i convert the HttpCookie to a String
string DateView = Convert.ToString(CurrDay.Value);
//Here i convert the String to DateTime
DateTime myDate = DateTime.ParseExact(DateView, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
After running the code I get the error:
FormatExeption was unhandled by user code
An exception of type 'System.FormatException' occurred in
mscorlib.dll but was not handled in user code
Additional information: String was not recognized as a valid DateTime.
1-11-2017 is not in the format of dd-MM-yyyy, specifically the first part. Use d-M-yyyy instead which will use one digit day and month when the value is below 10 (ie. no 0 padding).
Test:
DateTime myDate = DateTime.ParseExact("1-11-2017", "d-M-yyyy", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(myDate.ToString());
If you do not know if there will be 0 padding you can pass an array of acceptable formats, the parser will try each one in order they appear in the array.
DateTime myDate = DateTime.ParseExact("1-11-2017", new string[]{"d-M-yyyy", "dd-MM-yyyy"}, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
Fiddle
The Date format ddstands for The day of the month, from 01 through 31. You either supply it as 01-11-2017 or change your formatter to d-MM-yyyy.
Here's a reference to Custom Date and Time Format Strings
I solved this using yyyy-MM-dd instead of dd-MM-yyyy
(and later converting it to normal dates)
Becouse the var always was the day of today the day can be 1 and 2 digits
CurrDay.Value = DateTime.Now.ToString("yyyy-MM-dd" );
// Convert String to DateTime
dateFrom = DateTime.ParseExact(CurrDay.Value.ToString(), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
The comments below helped me find this solution,
Thanks to everyone!
Pass the value like below,
string DateView = Convert.ToString("01-11-2017");
DateTime myDate = DateTime.ParseExact(DateView, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
It's because ParseExact means you pass the format and the method expects the same date format to be passed as string, that's why you need to pass d-MM-yyyy instead of dd-MM-yyyy.
I you're not sure if the passed string will be with one digit or two then do the following:
string[] digits = DateView.split('-');
DateTime dateTime = new DateTime(digits[2], digits[1], digits[0]);
You even can split using / instead, but you need to make sure the first digit is a day and the second is month, and so on.
My advice is pass ticks instead of string of datetime:
DateTime date = new DateTime(numberOfTicks);
string valueAsStr = date.ToString("dd-mm-yyyy");

Add time duration to date using addHours() in c#

I want to add time duration to my datetime variable. I am reading the duration from a csv file. The format of duration is 0:29:40 or 1:29:40. When i add this to datetime variable it gives exception of incorrect format. How can I add the duration using this format. Previously I had duration as a simple integer like "6" or "7" but now the format is this "0:29:40" I don't know how to change my code to accommodate this format.
Previously i was doing this
double hours = Convert.ToDouble(row.Cells[2].Value.ToString());
DateTime newdate = finaldate.AddHours(hours);
row.Cells[2].Value.ToString() reads the value from csv
Any help is appreciated, Thanks
You don't need to parse to a double. Parse to a TimeSpan. Something like:
var source = "0:29:40";
var ts = TimeSpan.Parse(source);
Now ts is your time span. And the nice thing with TimeSpan is you can just add it to a DateTime:
DateTime newdate = finaldate + ts;
You are going to need to use the TimeSpan.Parse() or TimeSpan.ParseExact() method to properly parse your string and then simply add that TimeSpan result to your existing date:
var time = TimeSpan.Parse(row.Cells[2].Value.ToString());
DateTime newDate = finalDate.Add(time);
If you need to explicitly specify what each of the values of your time represent, then the TimeSpan.ParseExact() method will allow you to provide a formatting string to specify this:
// This will assume that 1:29:40 is hours, minutes, and seconds
var time = TimeSpan.ParseExact(row.Cells[2].Value.ToString(), #"h\:m\:s", null);

Get yesterday's date from the date entered

I have console application that accepts date as parameter. However, the date is passed as a string in this format:
string dt = DateTime.Now.ToString("yyyyMMdd");
Once the date is entered I need to programmatically get day - 1 from the entered date. Since this is a string, I cannot do any calculation.
For example, user enters:
20141023
I need to subtract a day from the date to get:
20141022
I did a quick fix to solve my immediate need, however, this is not the right way to do it and it has a bug:
int yt = Int32.Parse(dt) - 1;
And then I turn around and convert it yt.ToString()
The above solution will not work if it's the 1st of the month.
Is there a way I can programmatically get yesterday's date in the format (yyyyMMdd) without changing the format and possibly not using the TimeSpan?
Why don't parse the input into a DateTime object? Then you can use the DateTime.AddDays(-1)
For example:
var inputDate = DateTime.ParseExact("20141022", "yyyyMMdd", CultureInfo.InvariantCulture); // change "20141022" into the inputted value
var yesterday = inputDate.AddDays(-1);
var yesterdayString = yesterday.ToString("yyyyMMdd"); // this will be yesterdays date, in the string format
Try this...
DateTime data = DateTime.ParseExact("20141023", "yyyyMMdd", CultureInfo.InvariantCulture);
Console.WriteLine("{0} - {1}", data, data.AddDays(-1).ToString("yyyyMMdd"));
Would this work for you ?
string newDateTimeStr = (DateTime.Today.AddDays(-1)).ToString("yyyyMMdd");
EDIT:
for the date entered by the user:
string txtInputDate = Console.ReadLine();
DateTime dateTime = new DateTime(txtInputDate).ToLocalTime();
string newDateTimeStr = (dateTime.AddDays(-1)).ToString("yyyyMMdd");

C# WPF Time Until xx

I am trying to display the time remaining until a time specified by the user. I want to show Hours, Minutes, Seconds, and maybe milliseconds until the specified time.
DateTime remaining = DateTime.Parse("2/24/2014 18:00:00 pm");
DateTime startDate = DateTime.Now;
TimeSpan t = remaining - startDate;
string countdown = string.Format("{0}:{1}:{2}:{3}", t.Days, t.Hours, t.Minutes, t.Seconds);
CountDown.Content = countdown;
Visual Studio says I need to parse the string to take in the date before setting it to a DateTime object.
So do I need to create a new string, then parse it to a string, and then set the string to a DateTime object?
Update:
The actual error message I am receiving is:
System.FormatException was unhandled HResult=-2146233033
Message=String was not recognized as a valid DateTime. Source=mscorlib
If I understand the question correctly, you just want:
DateTime target = new DateTime(2014, 2, 24, 18, 0, 0);
TimeSpan remaining = target - DateTime.Now;
There's no need to parse a string just to get a DateTime value, if you already know the year/month/day etc you want.
However, you've also talked about "a time specified by the user". If that date/time is being specified as a string, then yes, you'll need to parse it. Ideally, it would be specified by some sort of date/time picker control, in which case you should just be able to get an appropriate DateTime value. Avoid string conversions unless you really need them.
This should get you going:
DateTime remaining = DateTime.Parse("2/24/2014 18:00:00 pm");
DateTime startDate = DateTime.Now;
TimeSpan t = remaining - startDate;
DateTime difference = new DateTime(t.Ticks);
CountDown.Content = difference;

How to convert HH:MM:SS string to datetime?

i am having an input string of HH:MM:SS for example 15:43:13,
now i want to convert it to datetime but keep just the hour/time without the date etc
is it possible?
for example
string userInput = 15:43:13;
DateTime userInputTime = Convert.ToDateTime(userInput);
will give me the full date including the year etc,
is there any way to convert it to just HH:MM:SS without triming/substring?
thanks
As others have said, it's a TimeSpan.
You can get a datetime by doing this
string userInput = "15:43:13";
var time = TimeSpan.Parse(userInput);
var dateTime = DateTime.Today.Add(time);
To just get a time span, you can use:
TimeSpan.Parse("15:43:13")
But you should ask yourself why you want to do this as there are some fairly significant gotchas. For example, which 2:33 AM do you want when it's Sunday, November 3, 2013, and daylight savings time is ending? There are two of them.
If you don't need the extra data (year etc.) use TimeSpan
You can convert from the user input to a TimeSpan using Timespan.Parse
for example:
TimeSpan ts = TimeSpan.Parse("6:12"); //06:12:00
Read more here:
http://msdn.microsoft.com/en-us/library/se73z7b9.aspx

Categories

Resources