C# Display Milliseconds in hh:mm:ss format - c#

I am trying to write a program that has the function to lock the computer after a specified amount of time once the program is activated. The problem im having is getting the time remaining to display properly. I am trying to do this using datetime vs a switch/if scenario. display a countdown timer based on a user specified about of time. More specifically what I want to do is
1) the user specifies amount of minutes
2) the minutes is programmatically converted to milliseconds
3 where im stuck) Milliseconds is converted and displayed via label in hh:mm:ss.
I have spent a couple days searching and I don't quite understand the MSDN examples and I haven't been able to come a cross the way to do this. Found plenty of examples for going from datetime to milliseconds though.

TimeSpan would be better suited since you're talking about a duration, not a point in time. You can create a TimeSpan from milliseconds and then format it with ToString():
int ms = 123456;
TimeSpan ts = TimeSpan.FromMilliseconds(ms);
Console.WriteLine(ts.ToString(#"hh\:mm\:ss"));

Related

Subtracting an unknown interval from a datetime

I am setting up a system to gather data from a database based on a user inputted start date and end date. The system will gather data averaged over an interval(1 hour, 6 hours, or one day for example). If the user does not input a start or end date I would like the program to set the start date to the current time minus the interval.
I currently have the user inputting the interval in the following format.
1m = 1 minute
1h = 1 hour
12h = 12 hours
3d = 3 days
So these values are not formatted like datetime. I could take the current datetime and subtract it by either minutes, hours, or days depending on the value appended (splitting on the number), but this would mean many if statements. What I would really like is a method to subtract a datetime by an arbitrary value Does anyone have a better solution?
Instead of providing predefined time intervals (that are implemented e. g. via a separate type/enum), it is much easier to let the user freely specify a TimeSpan.
This has two advantages:
The user is not restricted to predefined intervals
You can subtract the TimeSpan directly from your DateTime.Now
If restriction to limited intervals is a requirement, you can implement this in the view/window. But still this should be a TimeSpan.

Combining two Datetime values

I'm pretty new to coding so sorry if my question has an obvious answer but I didn't find anything like that via the search.
I'm currently trying to make a time tracker database by using Windows Forms in C#.
My oroblem is the GUI has two DateTimePicker: one displays the hours (dateTimePicker1) which you can choose, and the other one displays the minutes (dateTimePicker2) you can choose.
Both of them are starting with the current time when the form is loading.
I'm now trying to combine those two so that I get a string which gives me both hours and minutes with the chosen time.
If someone could help me here I'd be really glad because I'm currently out of ideas....
Do you mean like this?
// take hour from first datetimepicker
DateTime hour = dateTimePicker1.Value.Hour;
// take minute from second datetimepicker
DateTime minute = dateTimePicker2.Value.Minute;
// combine hour and minute into an object
DateTime hourAndMinute = hour + minute;
// convert the combined DateTime into string
hourAndMinute.ToString("hh:mm");
If you want to convert it to string with different format you can check it here http://www.dotnetperls.com/datetime-format
If you actually need to represent length of time you should use this one http://www.dotnetperls.com/timespan
Mark as an answer if it help you :)
Are you looking for this?
// myDatePicker displays date
DateTime day = myDatePicker.Value.Date;
// myTimePicker displays time
var timeOffset = myTimePicker.Value.TimeOfDay;
// combined value (day and time)
DateTime result = day + timeOffset;
In case you have three DatePickers (date, hour and minutes):
// myDatePicker displays date
DateTime day = myDatePicker.Value.Date;
DateTime result = day
.AddHours(myHourPicker.Value.Hour)
.AddMinutes(myMinutePicker.Value.Minute);
To display in required format use formatting:
// Hours and minutes
String text = result.ToString("hh:mm");

Recording and calculating rich elapsed times with Noda Time

I'd like to accurately track key instants for a session object (representing a remote resource), and here is what I would like to do:
Record key events, such as the session start time
Display rich time information to the user when asked
Have the ability to calculate elapsed times between any event, such as the time relative to the session start time
I have some test code where I can successfully gather all of the information that I need, and I'm using IClock as a basis to start with instants, from which I can create ZonedDateTime and LocalDateTime values. I've yet to find any examples other than calculating days and months (using Period). I need to record and display times (e.g. the elapsed time since the session started) at least down to the second.
Are they any examples like this out there? I searched around and have not found anything yet.
Using the BCL, this would be a job for TimeSpan. But I want the much richer data provided by Noda Time for a number of reasons (and for consistency in other areas where I am using Noda Time).
It sounds like you are just looking for the Duration structure. Something like this?
IClock clock = SystemClock.Instance;
Instant i1 = clock.Now;
// some time later...
Instant i2 = clock.Now;
Duration d = i2 - i1;
You may be able to find more examples by searching Stack Overflow using the nodatime tag.
See also, the core types quick reference in the Noda Time user guide.
If you need something more specific, please edit your question to elaborate. Thanks.

DateTime.Parse error

Our webservice uses the Datetime.parse method to convert data from an xml to DateTime format. It parses Date and time strings separately and adds it together like this -
DateTime.Parse(Date_string).add(TimeSpan.Parse(Time_string)).
Code was working fine except for a few hours last week. Time was showing as 12 hours ahead of actual time. For example, 01/01/2011 10:00:00 will be parsed as 01/01/2011 22:00:00. Most of the requests during that time were processed with datetime values 12 hours ahead of actual time though some were processed correctly. It is working fine now and haven't seen it after that.
Has anyone seen a issue like this?
You say "Code was working fine except for a few hours last week", but you didn't specify exactly when that was or what time zone you are in. Any chance it was around a daylight savings time change?
You shouldn't use TimeSpan.Parse at all. A TimeSpan does NOT represent the time-of-day, despite its appearance as hh:mm:ss. A TimeSpan represents a fixed DURATION of time.
If you really are given separate date and time strings, join them together before parsing, such as:
DateTime dt = DateTime.Parse(date_string + " " + time_string);
You should also be aware of the timezone implications of the string you are sending in. See the MSDN article on DateTime.Parse for further details.

Building a Datetime Object for SQL database insert

I'm working on a small web form that requires the user to input (among other things), the scheduled backup time of whatever server they're adding to the system. The problem is, I'm struggling to find out the best way to take the user input and build a DateTime object (which is what the database requires).
I only really care about the Day of Week, Time of Day (12 or 24 hour clock).
I thought about just creating an empty DateTime object and then just adding my input values from the user, but you can only get, not set, the day of week, time of day, etc.
I've been looking at the Calender asp control, which would work for the day of the week selection, but I can't seem to find any support of time of day.
Thanks.
I don't think you want to use a DateTime for a recurring event such as a backup. A DateTime is useful for storing a particular date and time, but not a "template" for a recurring event. Instead I'd use separate columns to store the day of week value (0-6) and time of date (minutes after midnight) for the event.
If you going to use datepicker here is one great sample for adding JQuery date picker using C#. That helped me including in my project evrn if I did know anything abaut JQuery and java sripts at all.
DateTime is a immutable value type. You cannot set anything on it.
Assumed that you stick with DateTime on the DB and you don't want to use a DateTimePicker control.
You have to specify how the day of week and the time should be represented in the DateTime. You can start with DateTime.MinValue, the 1.1.0001, 12:00 at midnight, and add the day of week and the time. unfortunately, a regular DateTime field in a SqlServer 2005 is not able to store this date. So lets move it to the year 2000. The 1.1.2000 was a Saturday. You could calculate the DateTime like this:
int dayOfWeek; // 0 = mon, 6 = son
DateTime time;
DateTime scheduleTime = new DateTime(2000, 1, (dayOfWeek + 2) % 6 + 1)
+ time.TimeOfDay;
But honestly, I wouldn't do it. It smells. I just answered your question. Listen to tvanfosson. He said everything that needs to be said.

Categories

Resources