C# WPF Time Until xx - c#

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;

Related

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);

DateTime parsing - unexpected result

I have datetime string
dateStr = "2017-03-21T23:00:00.000Z";
then I am calling
var date = DateTime.Parse(dateStr);
and unexpectedly my date equals
22.03.2017 00:00:00
I expected it to be 21.03.2017
What's going on here?
DateTime.Parse() is locale specific and will take into account your local time zone when parsing dates.
If you are in CET (Central European Time) during the winter your offset is one hour ahead of UTC. The date given is marked with a Z indicating it is in UTC, so DateTime.Parse() will adjust that to your local timezone.
There is an override that allows you to change that behaviour if you want, by specifying a specific DateTimeStyles enum. DateTimeStyles.AdjustToUniversal is what you are looking for as that should keep the DateTime as UTC.
And if you only want the date part afterwards, you can just call .Date on the DateTime object you got back from Parse()
So, something like this:
var date = DateTime.Parse(dateStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).Date;
if the date format does not change then you can use the below code to get date part from date string. But it is a bit risky due to its strict dependency on the input format.
string dateStr = "2017-03-21T23:00:00.000Z";
int year = Int32.Parse(dateStr.Substring(0, 4));
int month = Int32.Parse(dateStr.Substring(5, 2));
int day = Int32.Parse(dateStr.Substring(8, 2));
var date = new DateTime(year, month, day);
Console.WriteLine(date);
Because the format of type 'DateTime' variable is 'YYYY-MM-DD hh:mm:ss'.
If you run this code:
var dt = DateTime.Now;
Console.WriteLine(dt);
You'll see '24/03/2017 12:54:47'
If you have 'YYYY-MM-DD' format, add .ToString("dd-MM-yyyy"), then:
string dateStr = "2017-03-21T23:00:00.000Z";
var date = DateTime.Parse(dateStr).ToString("dd-MM-yyyy");
Result:'24-03-2017'

How to Convert Long format Date to Short format Date with Type DateTime in C#

I want convert long dateTime to only date in C#. and both in dateTime type
DateTime creationDate = DateTime.Now;
DateTime shortDate = creeationDate.Date;
A DateTime is a struct, which always has -- as the name suggests -- date and time components. You cannot remove the time and there is, as far as I know, no built-in date-only type in .NET (maybe there is in some 3rd party libraries).
You have already discovered the Date property of DateTime which returns an new DateTime with the time components set to 00:00:00.000.
If you only need to output your current date you must apply some formatting on the DateTime
DateTime creationDate = DateTime.Now;
string shortDate = creatationDate.ToString("yyyy-MM-dd"); //or whatever formatting you need.
If you need calculations on your date, but want to ignore the time component, you could initialize your date accordingly, as you have done in your code.
DateTime creationDate = DateTime.Now.Date; //sets time component to 00:00
DateTime otherDate = new DateTime(2016, 11, 2, 0,0,0); //also initializies with time 00:00
int diff = (int)(otherDate-creationDate).TotalDays; //number of days between the two dates

Determining how long a trip takes in minutes

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.

DateTime convert to Date and then back to DateTime in C#

I use this to convert DateTime value into Date and then I add 00:00:00 and 23:59:59 to make sure whole day is taken into consideration when counting stuff. I'm pretty sure it's wrong way of doing things. What would be the right way?
DateTime varObliczOd = DateTime.Parse(dateTimeWycenaPortfelaObliczDataOd.Value.ToShortDateString() + " 00:00:00");
DateTime varObliczDo = DateTime.Parse(dateTimeWycenaPortfelaObliczDataDo.Value.ToShortDateString() + " 23:59:59");
if dateTimeWycenaPortfelaObliczDataOd is of type DateTime, You can use:
dateTimeWycenaPortfelaObliczDataOd.Date
to get the date part only (time will be 00:00:00...).
If you want to get the very last tick of the date, you can use:
dateTimeWycenaPortfelaObliczDataOd.Date.AddDays(1).AddTicks(-1)
but you really better work with the next date (.AddDays(1)).
In any case, there is no need to convert to string and back to DateTime.
DateTime objects have a Date property which might be what you need.
You can use the following properties / methods on a DateTime object to get your values :
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Date;
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataOd.AddDayes(1).AddTicks(-1);
It would help to know why you're needing it, but this would work.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Date;
DateTime varObliczDo = varObliczOd.AddDays(1).AddSeconds(-1);
Using the Date attribute and then manipulating them directly to create the required time component - no need to bother with parsing and conversion.
You could use the Date property of the DateTime object to accomplish what you need.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Value.Date;
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataDo.Value.Date.AddDays(1);
If you really want it to end at 23:59:59 you can do:
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataDo.Value.Date.AddDays(1).AddSeconds(-1);
Will set varObliczDo to be your ending date with no time plus one day (at midnight). So if dateTimeWycenaPortfelaObliczDataDo was 2010-03-05 16:12:12 it would now be 2010-03-06 00:00:00.
Something like this maybe? I've typed this out of my head, there are probably some mistakes in the code.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.AddSeconds(-dateTimeWycenaPortfelaObliczDataOd.Seconds).AddMinutes(-dateTimeWycenaPortfelaObliczDataOd.Minutes).AddHours(-dateTimeWycenaPortfelaObliczDataOd.Hours);
DateTime varObliczDo = new DateTime(dateTimeWycenaPortfelaObliczDataDo.Year, dateTimeWycenaPortfelaObliczDataDo.Month, dateTimeWycenaPortfelaObliczDataDoDay, 23, 59, 59);
DateTime newDate = new DateTime( oldDate.Year, oldDate.Month, oldDate.Day, 23, 59,59 )
DateTime newDate = new DateTime( oldDate.Year, oldDate.Month, oldDate.Day, 0, 0, 0 )
You could work with TimeSpan:
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd - new TimeSpan(dateTimeWycenaPortfelaObliczDataOd.Hours, dateTimeWycenaPortfelaObliczDataOd.Minutes, dateTimeWycenaPortfelaObliczDataOd.Seconds);
Like that you avoid at least the parsing, which can fail depending on the local culture settings.

Categories

Resources