In my app I have a drop-down box of strings that shows possible hours in 12-hour time for the user to select. The possible values are:
9am
10am
11am
12pm
1pm
2pm
3pm
4pm
5pm
What code will convert one of these strings to a 24 hour integer? For example, 10am should be converted to 10 and 4pm should be converted to 16.
You can use DateTime.Parse(...) to get a DateTime value, and then reference the .Hour property for a result;
int h = DateTime.Parse("10am").Hour; // == 10
int h2 = DateTime.Parse("10pm").Hour; // == 22
DateTime.Parse is pretty liberal in what it allows, but obviously makes some assumptions internally. For example, in the above code, DateTime.Parse("10am") returns 10am on the current date in the current timezone (I think...). So, be aware of the context in which you use the API.
If you have a dropdown, why not set the values to be the integer values you desire:
<asp:DropDownList runat="server" ID="hours">
<asp:ListItem Value="9">9am</asp:ListItem>
<asp:ListItem Value="10">10am</asp:ListItem>
<!-- etc. -->
<asp:ListItem Value="17">5pm</asp:ListItem>
</asp:DropDownList>
Considering the times are continuous, you can simplify the logic:
var firstHourStr = box.Items[0].ToString();
var firstHour = int.Parse(firstHourStr.Replace("am", "").Replace("pm", ""));
if (firstHourStr.Contains("pm"))
{
firstHour += 12;
}
var selectedHour = firstHour + box.SelectedIndex;
If the hours are static, and you know the first hour, you could have a const and simplify the process by much with var selectedHour = FIRST_HOUR + box.SelectedIndex.
Also, I assumed valid formats as shown in the question.
Final note: You'll need to handle the 12pm case which causes problems, due to the nature of the hour 12 being a single second after "am".
You could use DateTime.Parse, but that would not play nicely with internationalization.
int hour = DateTime.Parse(stringValue).Hour;
Instead, just use DateTime objects in the ComboBox and format them using FormatString:
// In Constructor:
cbHours.Items.Add(new DateTime(2000, 1, 1, 8, 0, 0));
cbHours.Items.Add(new DateTime(2000, 1, 1, 10, 0, 0));
cbHours.Items.Add(new DateTime(2000, 1, 1, 13, 0, 0));
cbHours.FormatString = "h tt";
// In event handler
if (cbHours.SelectedIndex >= 0)
{
int hour = ((DateTime)cbHours.SelectedItem).Hour
// do things with the hour
}
Related
For my SteamBot I want to store the date and the time when the item is tradable again.
Example:
// DateNow = 05.06.2019 13:37:00
(+ 7 days due to Steam's trade policy)
// DateNow+7Days = 12.06.2019 13:37:00
// DateIneed = 13.06.2019 09:00:00
So the DateTime I need is CurrentDateTime + 7 Days + The rest to 9 o'clock
This is how far I come:
var date = DateTime.Now.AddDays(7);
Is there any smart way to always get the DateTime I need?
Language is C#
You can check if it is before 9 o'clock today, then set the time to 9, else add one day and set the time to 9, should be fairly easy I think.
var time = DateTime.Now;
var date = time.Hour <= 9
? time.Date.AddDays(7).AddHours(9)
: time.Date.AddDays(7).AddHours(9).AddDays(1);
The DateTime.Date field exposes just the date of a DateTime, you can then add an arbitrary TimeSpan to that to set the time of a DateTime object to whatever you want;
DateTime.Now.AddDays(7).Date.Add(new TimeSpan(9, 0, 0))
Check it out in action here: https://dotnetfiddle.net/l3X37y
Given the hour of the day may be past 9AM already, it's possible to end up with a DateTime less than 7 days, to counter this you can check if the hour of the day exceeds what you're going to set the DateTime to and add a day if it does, like so;
DateTime dt = DateTime.Now.AddDays(7);
dt = dt.Date.Add(new TimeSpan(dt.Hour >= 9 ? 1 : 0, 9, 0, 0))
See this one in action here: https://dotnetfiddle.net/lfVGis
In jquery I do this:
new Date(2009, 12, 1)).getTime()
and I got a huge number like this 1262304000000
How can I change the datetime variable in c# to get the same result that I would get in jquery?
The JavaScript getTime function returns the number of milliseconds since midnight on 1st January 1970.
So to get the same figure from a .NET System.DateTime object, you must subtract the epoch of 1st January 1970 and return the TotalMilliseconds property of the resulting TimeSpan:
var dateOfInterest = new DateTime(2009,12,1);
var epoch = new DateTime(1970,1,1);
var differenceInMilliseconds = (dateOfInterest - epoch).TotalMilliseconds;
C# has DateTime.Ticks Property but this doesn't exactly do with getTime(). Looks like there is no exactly equavalent in C#. You can divide result with 10.000 but still it calculates from 0001 year. Javascripts's getTime() method calculates from 1970.
Gets the number of ticks that represent the date and time of this
instance.
A single tick represents one hundred nanoseconds or one ten-millionth
of a second. There are 10,000 ticks in a millisecond.
The value of this property represents the number of 100-nanosecond
intervals that have elapsed since 12:00:00 midnight, January 1, 0001,
DateTime dt = new DateTime(2009, 12, 1);
dt.Ticks.Dump(); // 633952224000000000
From http://www.w3schools.com/jsref/jsref_gettime.asp
The getTime() method returns the number of milliseconds between
midnight of January 1, 1970 and the specified date.
As a better solution, you can use TimeSpan structure to subtract your dates and use TotalMilliseconds property like;
DateTime start = new DateTime(2009, 12, 1);
DateTime end = new DateTime(1970, 1, 1);
double miliseconds = (start - end).TotalMilliseconds;
miliseconds.Dump(); // 1259625600000
I need to compute the JavaScript getTime method in C#.
For simplicity, I chose a fixed date in UTC and compared the C#:
C#
DateTime e = new DateTime(2011, 12, 31, 0, 0, 0, DateTimeKind.Utc);
DateTime s = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
TimeSpan t = (e - s);
var x = t.TotalMilliseconds.ToString();
=> 1325289600000
and the JavaScript results:
JavaScript
var d = new Date(2011, 12, 31, 0, 0, 0)
var utcDate = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds());
utcDate.getTime()
=> 1327960800000
Any hints on what I'm doing wrong?
Thanks!
Javascript months are zero-based.
12 means January of next year.
You want 11.
If you meant for the input to be at UTC, you should be doing this instead:
var ts = Date.UTC(2011,11,31,0,0,0);
As SLaks pointed out, months run 0-11, but even then - you must initialize the date as UTC if you want the response in UTC. In your code, you were initializing a local date, and then converting it to UTC. The result would be different depending on the time zone of the computer where the code is running. With Date.UTC, you get back a timestamp - not a Date object, and it will be the same result regardless of where it runs.
From Chrome's debugging console:
This is the same value returned from your .NET code, which looks just fine, except I would return a long, not a string.
The date JS is wrong I believe. Omit the var utcDate line and output just d.getTime()
The time between two dates is the same, regardless of timezone and offset. Timezones are relative to an ACTUAL point in time, so whether you call .getTime() on the UTC or EST or PST date, it will be the same relative to 1970-1-1 of the same timezone.
2011-12-31 EST - 1970-1-1 EST
== 2011-12-31 PST - 1970-1-1 PST
== 2011-12-31 UTC - 1970-1-1 UTC
EDIT: Per #Slaks above, you also are not using the 0-based month (which I also had no idea about).
I'm having problems when I'm trying to substract hr2 with hr1 in a specific situation, for example, when hr1 = 13:00 and hr2 = 15:00, ok, the result is 02:00.
But when the values are: hr1 = 22:00 and hr2 = 02:00, the result is 20:00.
The result should be 04:00.
TimeSpan ts1 = hr1.Subtract(hr2).Duration();
TextBox1.Text = ts1.ToString();
How can I solve this problem?
I understand what you want, but how you currently try to achieve it makes no sense. 22 hours minus 20 hours is 2 hours, which is correct.
You probably want this:
new DateTime(1, 1, 2, 2, 0, 0) - new DateTime(1, 1, 1, 22, 0, 0)
You don't want to subtract TimeSpan's, you want to subtract dates (fake dates in this case).
Invoking Duration() will always result in a positive TimeSpan. The problem is coming from the fact that you are discarding days in your calculation. 22:00-02:00 is 20:00. I believe you are expecting it to be 04:00 because 02:00 represents "tomorrow." If that is what you want, you will need to calculate 22:00-(02:00+24:00) which will give you -04:00, which will become 04:00 when you invoke Duration().
You are trying to subtract two "spans", or durations, of time--not fixed points in time. What your code is currently saying is, I want to subtract two hours from twenty hours (which is indeed twenty hours). Instead, you need to use DateTimes. The hard part is going to be deciding the date for your timespans. I would rework the code to use DateTimes and preserve the "moments" in time that you are actually attempting to calculate.
Edit: Converting from a TimeSpan to a DateTime can cause you to lose information that affects the outcome of the result:
var ts1 = new DateTime (1, 1, 1, hr1.Hours, hr1.Minutes, hr1.Seconds, hr1.Milliseconds) -
new DateTime (1, 1, 1, hr2.Hours, hr2.Minutes, hr2.Seconds, hr2.Milliseconds);
is different than:
var ts1 = new DateTime (1, 1, 1, hr1.Hours, hr1.Minutes, hr1.Seconds, hr1.Milliseconds) -
new DateTime (1, 1, 2, hr2.Hours, hr2.Minutes, hr2.Seconds, hr2.Milliseconds);
or:
var ts1 = new DateTime (1, 1, 2, hr1.Hours, hr1.Minutes, hr1.Seconds, hr1.Milliseconds) -
new DateTime (1, 1, 1, hr2.Hours, hr2.Minutes, hr2.Seconds, hr2.Milliseconds);
Which is why you need to maintain the "point in time" with a DateTime.
Would appreciate it if anyone can help me figure out to substract 2 datetime fields to get the days left difference.
This is very easy to do with C#. For comparing DateTimes, we have a class called TimeSpan. The TimeSpan structure, in this case, would be defined as the difference between your two datetimes.
Let's say that your DateTimes are called start and end.
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
We have established our DateTimes to June 14, 2009 and December 14, 2009.
Now, let's find the difference between the two. To do this, we create a TimeSpan:
TimeSpan difference = end - start;
With this TimeSpan object, you can express the difference in times in many different ways. However, you specifically asked for the difference in days, so here's how you can get that:
Console.WriteLine("Difference in days: " + difference.Days);
Thus, the property is called TimeSpan.Days.
Final Code
//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
TimeSpan difference = end - start; //create TimeSpan object
Console.WriteLine("Difference in days: " + difference.Days); //Extract days, write to Console.
For more information on using the TimeSpan structure, see this MSDN documentation (especially the C# examples).
Hope I helped!
UPDATE: Some answers have suggested taking doing subtraction in one step, such as with:
int days = (dt2 - dt1).Days;
or
int numDaysDiff = Math.Abs(date2.Subtract(date1).Days);
However, they are the same thing as in my answer, only shortened. This is because the DateTime.Subtract() method and the subtraction operator of DateTimes returns a TimeSpan, from which you can then access the amount of days. I have specifically used the longer approach in my code sample so that you clearly understand what is going on between your DateTime and TimeSpan objects and how it all works. Of course, the other approaches I just mentioned are fine, too.
UPDATE #2:
A very similar question was asked before, and it can be found here. However, the main point of that question was why the code sample (which is essentially equivalent to that of all the answers) sometimes provides an answer which is a day off. I think this is also important to this question.
As the main answer to the other question suggests, you can use this code:
int days = (int)Math.Ceiling(difference.TotalDays);
This code uses Math.Ceiling, which, according to MSDN, is:
Returns the smallest integral value
that is greater than or equal to the
specified double-precision
floating-point number.
How Do You Want to Count the Days?
Thus, we now have an issue with how you want to count the days. Do you want to count part of a day (such as .5 of a day) as:
A full day - this would use Math.Ceiling to round up TimeSpan.TotalDays, so that you're counting started days.
Part of a day - you can just return the TimeSpan.TotalDays (not rounded) as a decimal (in the double datatype)
Nothing - you can ignore that part of a day and just return the TimeSpan.Days.
Here are code samples for the above:
Counting as a full day (using Math.Ceiling() to round up):
//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
TimeSpan difference = end - start; //create TimeSpan object
int days = (int)Math.Ceiling(difference.TotalDays); //Extract days, counting parts of a day as a full day (rounding up).
Console.WriteLine("Difference in days: " + days); //Write to Console.
Counting as part of a day (NOT using Math.Ceiling(), instead leaving in decimal form as a part of a day):
//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
TimeSpan difference = end - start; //create TimeSpan object
double days = difference.TotalDays; //Extract days, counting parts of a day as a part of a day (leaving in decimal form).
Console.WriteLine("Difference in days: " + days); //Write to Console.
Counting as nothing of a day (rounding down to the number of full days):
//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
TimeSpan difference = end - start; //create TimeSpan object
int days = difference.TotalDays; //Extract days, counting parts of a day as nothing (rounding down).
Console.WriteLine("Difference in days: " + days); //Write to Console.
Use
TimeSpan
DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0);
DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0);
TimeSpan travelTime = arrival - departure;
The easiest way out is, making use of TimeSpan().
This Subtract function will return you the difference between two dates in terms of time span. Now you can fetch fields like days, months etc. To access days you can make use of
Here is the sample code;
VB.Net code;
Dim tsTimeSpan As TimeSpan
Dim ldDate1 as Date
Dim ldDate2 as Date
'Initialize date variables here
tsTimeSpan = ldDate1 .Subtract(ldDate2)
Dim NumberOfDays as integer = tsTimeSpan.days
C#.Net code;
DateTime lDate1;
DateTime lDate2;
TimeSpan tsTimeSpan ;
int NumberOfDays;
//Initialize date variables here
tsTimeSpan = ldDate1 .Subtract(ldDate2);
NumberOfDays = tsTimeSpan.days;
DateTime dt1 = new DateTime(2009,01,01,00,00,00);
DateTime dt2 = new DateTime(2009,12,31,23,59,59);
int days = (dt2 - dt1).Days;
Number of Days Difference
These answers take the number of days as an int from the System.TimeSpan structure that is the result of subtracting two System.DateTime fields...
Quick answer - gets the number of days difference.
int numDaysDiff = date2.Subtract(date1).Days;
Alternate answer - uses Math.Abs to ensure it's not a negative number, just in case the dates might be supplied in either order.
int numDaysDiff = Math.Abs( date2.Subtract(date1).Days );
Some sample data to finish it off using System namespace:
// sample data
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(10);
MSDN References (and more sample code ):
System.TimeSpan structure
System.DateTime structure
System.Math.Abs(..) method
DateTime theDate = DateTime.Today;
int datediff = theDate.Subtract(expiryDate).Negate().Days;
if expiryDate > theDate then you get Negative value: -14
expiryDate is less than theDate then you get positive value: 14
You May obviously want this in a scenario such as
Send a Notification Email 14days before expiry
Send another notification Email 14 days after expiry
You need a difference that could be negative value
You should look at TimeSpan.
To get the exact days ignoring the time section
DateTime d1 = Convert.ToDateTime(DateTime.Now.ToShortDateString());
DateTime d2 = Convert.ToDateTime(DateTime.Now.AddDays(46).ToShortDateString());
var days = Convert.ToInt32(d2.Subtract(d1).TotalDays)