Compare DateTimeOffset with daylight saving time - c#

Here the DateTimeOffset instances represent the same time, but one instance has DST and other doesn't.
I would like to compare instances without DST, so the result would be True.
using System;
var today = DateTime.Today;
// Today YYYY-MM-01
var firstDayMonth = new DateTimeOffset(
new DateTime(today.Year, today.Month, 1, 0, 0, 0, today.Kind).AddHours(12));
// Add year offset from 2000
DateTimeOffset withYearOffset = firstDayMonth.AddYears(2000 - firstDayMonth.Year);
// Add month offset from 1
var withMonthOffset = withYearOffset.AddMonths(1 - withYearOffset.Month);
// Add day offset from 1
var calculated_dt_2000_1_1_12_0_0 = withMonthOffset.AddDays(1 - withMonthOffset.Day);
// 01.01.2000 12:00:00 +03:00
Console.WriteLine(calculated_dt_2000_1_1_12_0_0);
var dt_2000_1_1_12_0_0 = new DateTimeOffset(new DateTime(2000, 1, 1).AddHours(12));
// 01.01.2000 12:00:00 + 02:00
Console.WriteLine(dt_2000_1_1_12_0_0);
// False
Console.WriteLine(calculated_dt_2000_1_1_12_0_0.Equals(dt_2000_1_1_12_0_0));

Converting to UTC solves the problem.
var calculated_dt_2000_1_1_12_0_0 = withMonthOffset.ToUniversalTime().AddHours(firstDayMonth.Offset.Hours);
var dt_2000_1_1_12_0_0_withOffset = new DateTimeOffset(new DateTime(2000, 1, 1).AddHours(12));
var dt_2000_1_1_12_0_0 = dt_2000_1_1_12_0_0_withOffset.ToUniversalTime().AddHours(dt_2000_1_1_12_0_0_withOffset.Offset.Hours);

Related

Add one hour to summer dst

I have the follow code to get the local time in ms:
var dtNow = DateTime.Now;
var time = TimeSpan.FromMilliseconds((dtNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).ToLocalTime()).TotalMilliseconds);
long end_time = Convert.ToInt64(time.TotalMilliseconds);
The time object indicate to correct hour (11:20:00) but the ms object indicate on 12:20:00, Why its happend and how i can fix it?
Before the summer dst Its works perfecr.
Thanks!
Because your dtNow = DateTime.Now; is local and with (dtNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).ToLocalTime()) you're converting the time to local again .ToLocalTime()
Try:
var dtNow = DateTime.UtcNow;

Check if any dates within a range fall within a specified month

I am at a bit of a loss as to the best approach. Let's say I have the following:
//Get the first and last day of the month -- ex February
int month = DateTime.ParseExact("February", "MMMM", new CultureInfo("en-US")).Month;
var now = DateTime.Now;
var firstOfMonth = new DateTime(now.Year, month, 1);
var lastOfMonth = new DateTime(now.Year, month, DateTime.DaysInMonth(now.Year, month));
var coverageStartDate = new DateTime(now.Year, 1, 1);
var coverageEndDate = new DateTime(now.Year, 2, 15);
I am trying to create a check to see if the date range of coverageStartDate and coverageEndDate falls in the month of February. Keep in mind that the values could also look like:
var coverageStartDate = new DateTime(now.Year, 2, 3);
var coverageEndDate = new DateTime(now.Year, 2, 10);
As long as there is a single date in the coverage start / end date range falls in the month of February, I would want to return true.
With DateTime you can use >=, <=, etc.
Adopting your code, I would do something like this:
var firstOfMonth = new DateTime(now.Year, month, 1, 0, 0, 0);
var lastOfMonth = new DateTime(now.Year, month, DateTime.DaysInMonth(now.Year, month), 23, 59, 59);
var coverageStartDate = new DateTime(now.Year, 1, 1);
var coverageEndDate = new DateTime(now.Year, 2, 15);
if(coverageStartDate <= lastOfMonth && coverageEndDate >= firstOfMonth)
{
// Do something
}
This code does not requires that years have to be the same, so the coverage time can span multiple years.

Get total hours that fall between a specific time period

the condition is Time in and Time out (e.g 02/01/2015 02:55 'til 02/02/2015 05:55) that is more than a day. I already computed the total hours of Time in and Time out, and I want to know if the total hours has passed between 23:00(11:00PM ) up to 06:00AM and get the total of it
var hours = (datevalue1 - datevalue2).TotalHours;
or
Timespace ts= (datevalue1 - datevalue2);
var hours = ts.Value.TotalHours;
Try this way.. DateTime.Parse().Subtract()
eg:
string startTime = "11:00 PM";
string endTime = "6:00 AM";
TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));
Console.WriteLine(duration);
Console.ReadKey();
OR
TimeSpan is the object you need:
TimeSpan span = (DateTime.Now - DateTime.Now);
String.Format("{0} days, {1} hours, {2} minutes, {3} seconds",
span.Days, span.Hours, span.Minutes, span.Seconds);
You can calculate it by passing over time. when its night time add it to TimeSpan.
DateTime timeIn = new DateTime(2015, 09, 29, 10, 11, 3); // 29-09-2015 at 10:11:03
DateTime timeOut = new DateTime(2015, 10, 1, 2, 19, 18); // 01-10-2015 at 02:19:38
TimeSpan nightTime = new TimeSpan(); //total amount of night time
TimeSpan passLength = new TimeSpan(0, 0, 0, 1); // length of time to pass at each iteration (1s)
while (timeIn < timeOut) // do it until timeIn reaches timeOut
{
timeIn = timeIn.Add(passLength); // add 1 second to timeIn
if (timeIn.Hour < 6 || timeIn.Hour == 23) // if we are in range of night time
{
nightTime = nightTime.Add(passLength); // add 1 second to night time
}
}
Console.WriteLine(nightTime);
You can do lot of optimizations. for long times its not good idea to add 1 sec each time. you can add 1 day to TimeIn at each iterate then add only 6 hours to night time. after you get close to Timeout decrease length time
Here is a better way. first get days fast. then get rest of the time.
DateTime timeIn = new DateTime(2015, 09, 29, 10, 11, 3); // 29-09-2015 at 10:11:03
DateTime timeOut = new DateTime(2015, 10, 1, 2, 19, 18); // 01-10-2015 at 02:19:38
// Get days
TimeSpan passLength = new TimeSpan(1, 0, 0, 0); // one day per iterate
while (timeIn + passLength < timeOut)
{
timeIn = timeIn.Add(passLength);
nightTime = nightTime.Add(new TimeSpan(0, 7, 0, 0)); // 7 hours of a day passed is considered night time
}
// Get rest of the time
passLength = new TimeSpan(0, 0, 0, 1); // one second per iterate
while (timeIn < timeOut) // do it until timeIn reaches timeOut
{
timeIn = timeIn.Add(passLength); // add 1 second to timeIn
if (timeIn.Hour < 6 || timeIn.Hour == 23) // if we are in range of night time
{
nightTime = nightTime.Add(passLength); // add 1 second to night time
}
}
Console.WriteLine(nightTime);
You shouldn't be worry about rest of the time calculation performance. since the rest of the time is now less than 1 day which is only 86400 seconds.
Less than 86400 iterates should be fine for today's processors speed. how ever you can still optimize it farther away but you don't get much more performance.
A little bit different and faster approach:
static void Main(string[] args)
{
TimeSpan result = new TimeSpan();
DateTime dt1 = new DateTime(2015, 09, 29, 10, 11, 03);
DateTime dt2 = new DateTime(2015, 10, 01, 02, 19, 38);
DateTime d1 = new DateTime(dt1.Year, dt1.Month, dt1.Day, 0, 0, 0); //Date only
DateTime d2 = new DateTime(dt2.Year, dt2.Month, dt2.Day, 0, 0, 0); //Date only
//Count night time in first day
result += DateTime.Compare(dt1, d1.AddHours(6)) > 0 ? new TimeSpan(6, 0, 0) : new TimeSpan(dt1.Hour, dt1.Minute, dt1.Second);
if (DateTime.Compare(dt1, d1.AddHours(23)) > 0) result += new TimeSpan(dt1.Hour - 23, dt1.Minute, dt1.Second);
//Count night time in last day
result += DateTime.Compare(dt2, d2.AddHours(6)) > 0 ? new TimeSpan(6, 0, 0) : new TimeSpan(dt2.Hour, dt2.Minute, dt2.Second);
if (DateTime.Compare(dt2, d2.AddHours(23)) > 0) result += new TimeSpan(dt1.Hour - 23, dt2.Minute, dt2.Second);
//Count night time in middle days
int daysBetween = (int)(d2 - d1).TotalDays - 1;
result += new TimeSpan(daysBetween * 7, 0, 0);
Console.WriteLine("Night time: " + result);
Console.ReadKey();
}
Compare EndTime with your Range(23:00-06:00)
that is in your Case, check wether EndTime 05:55 < 06:00 and EndTime 05:55 > 23:00
You can subtract the DateTime values to get the TimeSpan in between. Then you can get the TotalHours in that
var hours = timeOut.Subtract(timeIn).TotalHours;
For example
timeIn = 29-09-2015 10:11:03;
timeOut = 01-10-2015 02:19:38;
hours = 52.14303137125;

Determining if a UTC time is within DST

In C#, given a UTC time, how can I determine whether this falls within DST in Houston, Texas, US?
var utcDateTime = new DateTime(2013,1,1,0,0,0,DateTimeKind.Utc);
//bool fallsWithinDstInAmerica = ...?
Get the appropriate TimeZoneInfo for Texas, then use IsDaylightSavingTime.
using System;
class Test
{
static void Main()
{
// Don't be fooled by the "standard" part - this is Central Time
var zone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var winter = new DateTime(2013, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var summer = new DateTime(2013, 6, 1, 0, 0, 0, DateTimeKind.Utc);
Console.WriteLine(zone.IsDaylightSavingTime(winter)); // False
Console.WriteLine(zone.IsDaylightSavingTime(summer)); // True
}
}
Or using Noda Time, you can find the amount of daylight saving, and compare it with an offset of 0:
using System;
using NodaTime;
class Test
{
static void Main()
{
var zone = DateTimeZoneProviders.Tzdb["America/Chicago"];
var winter = Instant.FromUtc(2013, 1, 1, 0, 0);
var summer = Instant.FromUtc(2013, 6, 1, 0, 0);
Console.WriteLine(zone.GetZoneInterval(winter).Savings); // +00
Console.WriteLine(zone.GetZoneInterval(summer).Savings); // +01
Console.WriteLine(zone.GetZoneInterval(winter).Savings != Offset.Zero); // False
Console.WriteLine(zone.GetZoneInterval(summer).Savings != Offset.Zero); // True
}
}

How to get the current time in Jerusalem with C#?

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.

Categories

Resources