How to compare current time with another time..
System.DateTime.Now.Hour
This is for get cuurent hour.
What I want is if the time is in between
7 AM to 02:59 PM //Do something
03:00 PM to 10:59 PM //Do something
11:00 PM to 06:59 AM //Do something
Please give me any ideas..?
You may use DateTime.TimeOfDay property to compare the time with the current time.
TimeSpan startTime = new TimeSpan(7,0,0);
TimeSpan endTime = new TimeSpan(2, 59, 0);
if (DateTime.Now.TimeOfDay >= startTime &&
DateTime.Now.TimeOfDay <= endTime)
{
//in range
}
else
{
//not in range.
}
You can actually do arithmetic operations on DateTime, and it returns a timespan.
DateTime d1 = new DateTime(2012, 12, 12, 5, 5, 5);
DateTime d2 = DateTime.Now;
TimeSpan ts = new TimeSpan();
ts = d2 - d1;
Related
For example, I will be given a time on hours with type DateTime hours like this
for the starter
my starttime is 00:00
endtime is 02:00
and every time 30 minutes I like to input the value into a List<DateTime>
so, how can I get the value to put into a list that is look like this?
00:00
00:30
01:00
01:30
02:00
My Code
DateTime starTime = new DateTime();
DateTime endTimes = new DateTime();
DateTime interval = new DateTime();
List<DateTime> intervals = new List<DateTime>();
starTime = DateTime.ParseExact(fulldate + "00:00",
"yyyy/MM/dd HH:mm",
CultureInfo.InvariantCulture);
endTimes = DateTime.ParseExact(fulldate + "02:00",
"yyyy/MM/dd HH:mm",
CultureInfo.InvariantCulture); ;
interval = starTime;
for (int i = 0; i < 24; i++)
{
interval.AddHours(0.5);
intervals.Add(interval);
if (interval.ToString("HH:mm") == endTimes.ToString("HH:mm"))
{
break;
}
}
Can anyone help me to solve this?
With some assumption (that end time is on the same day, that your end time is always something that can be devided by 30 mins, ...) this would work.
var start = new TimeSpan(0, 0, 0);
var end = new TimeSpan(2, 0, 0);
var current = start;
List<DateTime> values = new List<DateTime>();
var startDate = DateTime.Now.Date; // editited after #pinkflowydx33's comment
values.Add(startDate + start);
while (current < end)
{
current = current.Add(new TimeSpan(0, 30, 0));
values.Add(startDate + current);
}
foreach (var v in values)
{
Console.WriteLine(v);
}
i prepared that type of solution. - It's loop over number, which represent - times of valueToChange - in this specific case between 30 minutes - and add to the startDate - 30 minutes and also saving to list.
using System;
public class Program
{
public static void Main()
{
List<DateTime> intervals = new List<DateTime>();
var changeValue = 30;
var startDate = new DateTime(2010, 05, 12, 13, 00, 00);
var endDate = new DateTime(2010, 05, 12, 14, 00, 00);
var timeIntervals = System.Math.Abs(startDate.Subtract(endDate).TotalMinutes / changeValue);
for (int i = 0; i < timeIntervals; i++)
{
startDate.AddMinutes(30);
intervals.Add(startDate)
}
}
}
In this case the start and end date are divided by 30 minutes without rest - so if there will be 13:00 and 13:12 - it's doesn't add the value to List - cause the value doesn't > 30.
I think the best way to describe this is to use examples. The range is between 4:00am and 4:00pm. At 0%, I want to get 4:00am back. At 100%, I want to get 4:00pm back. At 50%, I want to get 10:00am back.
The question is, how do I get this functionality with this signature?
string GetTime(percentage, startTime, endTime)
Assuming both DateTimes are in the same timezone, and that there isn't a transition (DST started/ended, local hour changed, etc):
public static void Main()
{
var startTime = new DateTime(2019, 01, 01, 4, 0, 0);
var endTime = new DateTime(2019, 01, 01, 16, 0 , 0);
// prints 10:00 AM
Console.WriteLine(GetTime(0.5, startTime, endTime));
}
private static string GetTime(double percentage, DateTime startTime, DateTime endTime)
{
// get the difference between the dates
// you could use TotalSeconds or a higher precision if needed
var diff = (endTime - startTime).TotalMinutes;
// multiply the result by the percentage
// assuming a range of [0.0, 1.0]
double minutes = diff * percentage;
// add the minutes (or precision chosen) to the startTime
var result = startTime.AddMinutes(minutes);
// and get the result
return result.ToShortTimeString();
}
You can test that in this fiddle: https://dotnetfiddle.net/g4gHLJ
You should return a TimeSpan instead of a string. Here's how I would do it:
static TimeSpan GetTime(double percentage, TimeSpan startTime, TimeSpan endTime)
{
var percentageInTicks = (long)((endTime - startTime).Ticks * percentage);
return startTime.Add(TimeSpan.FromTicks(percentageInTicks));
}
Usage:
TimeSpan startTime = new TimeSpan(4, 0, 0);
TimeSpan endTime = new TimeSpan(16, 0, 0);
double[] percentages = new[] { 0, 0.5, 1 };
foreach (double percentage in percentages)
{
var result = GetTime(percentage, startTime, endTime);
Console.WriteLine(result.ToString());
}
Output:
04:00:00
10:00:00
16:00:00
Edit: You can do basically the same thing with DateTime if you wish:
static TimeSpan GetTime(double percentage, DateTime startDate, DateTime endDate)
{
var percentageInTicks = (long)((endDate - startDate).Ticks * percentage);
return startDate.TimeOfDay.Add(TimeSpan.FromTicks(percentageInTicks));
}
Usage:
DateTime startDate = DateTime.Today.Add(new TimeSpan(4, 0, 0));
DateTime endDate = DateTime.Today.Add(new TimeSpan(16, 0, 0));
double[] percentages = new[] { 0, 0.5, 1 };
foreach (double percentage in percentages)
{
var result = GetTime(percentage, startDate, startDate);
Console.WriteLine(result.ToString());
}
Here's how to do it with just DateTimes as inputs and outputs:
public static DateTime GetTime(double percentage, DateTime startTime, DateTime endTime)
{
TimeSpan diff = endTime - startTime;
long percentOfTimeAsTicks = (long) (percentage * diff.Ticks);
return startTime + new TimeSpan(percentOfTimeAsTicks);
}
As #MattJohnson pointed out, the two DateTimes need to be on the same basis (either both UTC or both in the same timezone with the same summer/winter status).
Using Ticks rather than seconds or minute will give you the most precision.
Here's a simple test:
var start = DateTime.Today;
var end = DateTime.Now;
Debug.WriteLine(Struct128.GetTime(0.5, start, end));
That prints out a time just before 9:00 am (it's currently just before 6:00 pm here).
First you'll need to figure out the length of time between the start and end time and calculate the fraction of that that needs to be added to the start time...
DateTime GetTime(double percentage, DateTime startTime, DateTime endTime)
{
var duration = endTime - startTime;
var partDuration = percentage * (double)duration.TotalMilliseconds;
return startTime.AddMilliseconds(partDuration);
}
GetTime(0.5, DateTime.Today.AddHours(4), DateTime.Today.AddHours(16)).Dump();
I need to know Jerusalem Current time.
That code taking server time but I need Jerusalem time:
DateTime currentTime = DateTime.Now;
dayName = currentTime.DayOfWeek;
Edit:
with help of Vinoth answer(I took only the AddHours(2) part) it should be like that (not works):
DateTime currentTime = DateTime.Now;
currentTime=currentTime.AddHours(2);//Jerusalem Time
dayName = currentTime.DayOfWeek;
Edit2:my improvement (ToUniversalTime())
DateTime currentTime = DateTime.Now;
currentTime=currentTime.ToUniversalTime().AddHours(2);//Jerusalem Time
dayName = currentTime.DayOfWeek;
This will help you. I have used this is one of my app. Jus pasting the code
public static DateTime GetIsraelTime(DateTime d) {
d = d.AddHours(2); // Israel is at GMT+2
// April 2nd, 2:00 AM
DateTime DSTStart = new DateTime(d.Year, 4, 2, 2, 0 ,0);
while (DSTStart.DayOfWeek != DayOfWeek.Friday)
DSTStart = DSTStart.AddDays(-1);
CultureInfo jewishCulture = CultureInfo.CreateSpecificCulture("he-IL");
System.Globalization.HebrewCalendar cal =
new System.Globalization.HebrewCalendar();
jewishCulture.DateTimeFormat.Calendar = cal;
// Yom HaKipurim, at the start of the next Jewish year, 2:00 AM
DateTime DSTFinish =
new DateTime(cal.GetYear(DSTStart)+1, 1, 10, 2, 0 ,0, cal);
while (DSTFinish.DayOfWeek != DayOfWeek.Sunday)
DSTFinish= DSTFinish.AddDays(-1);
if (d>DSTStart && d<DSTFinish)
d = d.AddHours(1);
return (d);
}
var israelTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "Israel Standard Time")
Complete time zones ids list can be found here.
having a DateTime variable, for example:
DateTime testDate = new DateTime(2011,12,15,00,00,00);
how can I implement a foreach loop for every hour of this day?
Something like:
foreach (int myHour in testDate.Date)
{
}
but in this way does not compile.
It is not a good idea to loop 24, because this will not work on days with 25 or 23 hours (time change, daylight saving...).
Use the AddHour function and a target date.
DateTime testDate = new DateTime(2011, 12, 15, 00, 00, 00, DateTimeKind.Local);
DateTime endDate = testDate.AddDays(1);
while (testDate.Date != endDate.Date)
{
Console.WriteLine(testDate.ToString());
testDate = testDate.AddHours(1);
}
More Information
MSDN - DateTimeKind Enumeration
Use for instead:
DateTime date = new DateTime(2011,12,15);
for(int i = 0; i < 24; i++)
{
DateTime time = date.AddHours(i);
...
}
If you really want to use foreach, you could create an extension method like this:
static class DateTimeExtensions
{
public static IEnumerable<DateTime> GetHours(this DateTime date)
{
date = date.Date; // truncate hours
for(int i = 0; i < 24; i++)
{
yield return date.AddHours(i);
}
}
}
...
DateTime date = new DateTime(2011,12,15);
foreach (DateTime time in date.GetHours())
{
...
}
For those who don't like plain old for loops :) :
DateTime testDate = new DateTime(2011,12,15,00,00,00);
foreach (int hour in Enumerable.Range(0,24)) {
DateTime dateWithHour = testDate.AddHours(hour);
}
foreach loop works in list but here testDate.Date never gives you hour. so in substitution of it use for loop or do while or while loop.
The code below allows you to cycle through the hours of the day but also starting from a specific hour. It could be simpler if you do not need to support starting from an hour offset.
DateTime testDate = new DateTime(2011,12,15,13,00,00);
var hoursLeft = 24 - testDate.Hour;
for (var hour = 1; hour < hoursLeft; hour++)
{
var nextDate = testDate.AddHours(hour);
Console.WriteLine(nextDate);
}
To get the hours in DLS time use this:
DateTime testDate = new DateTime(2017, 03, 26, 00, 00, 00, DateTimeKind.Local);
DateTime endDate = testDate.AddDays(1);
//these dates also contain time!
var start = TimeZone.CurrentTimeZone.GetDaylightChanges(testDate.Year).Start;
var end = TimeZone.CurrentTimeZone.GetDaylightChanges(testDate.Year).End;
var hoursInDay = new List<DateTime>();
while (testDate.Date != endDate.Date)
{
if (start == testDate)
{
//this day have 23 hours, and should skip this hour.
testDate = testDate.AddHours(1);
continue;
}
hoursInDay.Add(testDate);
if (end == testDate)
{
hoursInDay.Add(testDate); //this day has 25 hours. add this extra hour
}
testDate = testDate.AddHours(1);
}
I'm in Denmark, so when I run this it has only 23 hours.
Iterate over all 24 hours of the day:
DateTime testDate = new DateTime(2011, 12, 15);
for (int i = 0; i < 24; i++)
{
DateTime hour = testDate.Date.AddHours(i);
// Your code here
}
DateTime today = DateTime.Today;
DateTime tomorrow = today.AddDays(1);
for ( var i = today; i <= tomorrow; i = i.AddHours(1))
{
// your code
}
simply do this
DateTime testDate = new DateTime(2011, 12, 15, 10, 00, 00);
for (int i = testDate.Hour; i < 24; i++)
{
//do what ever
}
I would like to define the start time as 6pm and end time as 9pm. This time range (something looked like below) used for everyday's schedule. How do I implement in for loop? Appreciate for any reply.
6:00 PM
6:30 PM
7:00 PM
7:30 PM
8:00 PM
8:30 PM
9:00 PM
you could use while loop
var startTime = DateTime.Parse("2012-01-28 18:00:00");
var endTime = startTime.AddHours(3);
while (startTime <= endTime)
{
System.Console.WriteLine(startTime.ToShortTimeString());
startTime = startTime.AddMinutes(30);
}
Simple example with TimeSpan:
for (int minutes = 6 * 60; minutes <= 9 * 60; minutes += 30)
{
Console.WriteLine(TimeSpan.FromMinutes(minutes));
}
you can try using DateTime.Now.Hour to get the hour and use if clauses. see exemple below
if (DateTime.Now.Hour >= 9 && DateTime.Now.Hour <= 18) { Console.WriteLine("Bonjour " + Environment.UserName); }
else
{
Console.WriteLine("Bonsoir " + Environment.UserName);
}
if u r going through current date with a time range from like 10:00:00 AM to 17:00:00 PM then u could use the below code
DateTime startTime = DateTime.Parse("10:00:00");
DateTime endTime = DateTime.Parse("17:00:00");
while (startTime <= endTime)
{
System.Console.WriteLine(startTime.ToShortTimeString());
startTime = startTime.AddMinutes(30);
}
When you use TimeSpan (time instead of Time and Date in DateTime)
TimeSpan interval = new TimeSpan(0, 30, 0);
TimeSpan beginTime = new TimeSpan(18, 00, 00);
TimeSpan endTime = new TimeSpan(21, 00, 00);
for(TimeSpan tsLoop = beginTime; tsLoop < endTime; tsLoop = tsLoop.Add(interval))
{
}