Reminder Service in C#.Net 4.0 using UTC Time - c#-4.0

I have a Windows Service that runs on my
Texas origin Server Central Time.
This will check for all active reminders and compares the reminder time that user wants and send out reminder if it matches with user required time.
Scenarios
User is from EST
User set up a reminder for *1:25 PM * using UI via my website
On submit, my C# business logic converts this time to UTC before storing in my database. That will become '18:25:00'
My Business logic will pull all Active reminders from DB
And checks for reminder time if current UTC time and Reminder setup time diffrence is less then 5 mins, then it will send notification to that customer.
this is how my logic written
DateTime CurrentDate = DateTime.Now.ToUniversalTime();
TimeSpan currentTime = DateTime.Now.ToUniversalTime().TimeOfDay;
if (Reminder.DailyReminders.Any(x => currentTime.Subtract(x.ReminderTime).TotalMinutes < 5
&& currentTime.Subtract(x.ReminderTime).TotalMinutes > 0))
{
if (Reminder.ReminderMedhodID.Equals(1))
_email.ComposeEmail(Reminder);
}
My Problem is
*currentTime* is always 1 hour behind to user requested reminder time SO my reminders are going out 1 hour late.
Note : currentTime is from below
TimeSpan currentTime = DateTime.Now.ToUniversalTime().TimeOfDay;
I am not sure if this is the best way to handle this requirement. considering this is one of the way, can any on help how to fix this issue?
Thanks to peter's answer
Can any one help me how to take user input time with Daylight consideration
This what i have so far
public TimeSpan ConvertToUTCTime(string dateStr)
{
DateTime localDateTime = DateTime.Parse(dateStr); // Local .NET timeZone.
DateTime utcDateTime = localDateTime.ToUniversalTime();
string clTimeZoneKey = TimeZone.CurrentTimeZone.StandardName;
TimeZoneInfo clTimeZone = TimeZoneInfo.FindSystemTimeZoneById(clTimeZoneKey);
DateTime clDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, clTimeZone);
if (clTimeZone.IsDaylightSavingTime(localDateTime))
{
// Get DayLight local time in UTC
// Yet to be implemented
}
return clDateTime.TimeOfDay;
}
I got this worked using this
http://msdn.microsoft.com/en-us/library/system.globalization.daylighttime.aspx

Ummm...we are currently using Daylight Saving Time in most of the U.S. (though there are some portions of Indiana that did/do use EST?) Since EDT is one hour ahead of EST, your logic is correct. It is the input (EST) that is incorrect.

Related

Are Alexa skill dates the same in the Service Simulator and the Echo?

My Alexa node.js skill involves getting the current date using "new Date()". In the Service Simulator the date returned is UTC. But I need the time in "America/New_York" -- my skill is local to New York. So I can convert the time zone, no problem. But I'm wondering whether this will get the same result when I deploy the skill. That is, does the Date() function on the actual Service convert to local time from UTC? If it does, then I will need some way of determining in my code whether I am in the Service Simulator or the actual Service, and converting to New York time in my accordingly.
Thank you.
From the documentation for Date
If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings.
So depending on the system settings the timezones can be different.
To overcome this you can use UTC date everywhere and then simply convert the timezone where needed.
// date with some timezone depending on system
let date = new Date();
// date in UTC
let utcDate = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
Note: utcDate will still be in the system timezone, but the actual value it holds will represent the correct date and time in UTC.

Quartz 2.2.3 TimeZone issue

I want to schedule the cron job according to the specified time zone. It will fire fine for first time but next time it will not firing according to the specified time zone rather it is firing according to the system's time.
Trigger trigger = TriggerBuilder.newTrigger().withDescription(jobPojo.getDescription()).withIdentity(jobPojo.getTriggerName(), jobPojo.getTriggerGroup())
.withSchedule(CronScheduleBuilder.cronSchedule(jobPojo.getExpression().trim()).inTimeZone(TimeZone.getTimeZone(jobPojo.getTimeZone())).withMisfireHandlingInstructionIgnoreMisfires()).usingJobData(jobDataMap).forJob(jobKey).build();
// As i am passing timezone in json pojo eg: jobPojo.getTimeZone() ="GMT+4:00" which is Dubai timezone Id . my system is running in India.
below is my fetching code :
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Trigger trigger = scheduler.getTrigger(triggerKey);
jobPojo.setNextFireTime(dateFormat.format(trigger.getNextFireTime()));
thanx in advance ..

How to get the local timezone from the system using nodejs

Is there a way to obtain the local timezone from the system (eg:- ubuntu) using nodejs?
I used moment.js to extract the date and time values. But couldn't find a way to extract the timezone as well.
The existing answers will tell you the current timezone offset, but you will have issues if you are comparing historic/future points in time as this will not cater for daylight saving changes.
In many timezones, the offset varies throughout the year and these changes occur at different dates or not at all depending on the latitude. If you only have UTC time and an offset, you can never be sure what the offset will be in that location at various other times during the year.
For example, a UTC+2:00 offset could refer to Barcelona in the summer or Ivory Coast all year round. The 2hr offset will always display the correct time in Ivory Coast but will be 1hr out for half the year in Barcelona.
Check out this great article covering the above.
How do we cater for all these time zone issues? Well, it's pretty simple:
Save all times in UTC
Store the time zone string for where this event occurred
In modern browsers or node.js, you can get the local IANA time zone string like this:
Intl.DateTimeFormat().resolvedOptions().timeZone // eg. 'America/Chicago'
You can then use this timezone string in a library like Luxon to help offset your captured UTC times.
DateTime.fromISO("2017-05-15T09:10:23", { zone: "Europe/Paris" });
It is very simple.
var x = new Date();
var offset= -x.getTimezoneOffset();
console.log((offset>=0?"+":"")+parseInt(offset/60)+":"+String(offset%60).padStart(2, "0"))
And there is nothing else or you can see if momentJS can help you or not.
Note: This answer is outdated, you can suggest to add in it.
It is this easy, no libraries needed:
console.log("test ...")
let d = new Date()
console.log("UTC time " + d)
let ank = d.toLocaleString('en-US', { timeZone: 'America/Anchorage' });
console.log("your time zone " + ank)
How to see the exact time zone names on most servers:
ls /usr/share/zoneinfo
Works flawlessly:
You'll get the correct time-text regardless of daylight savings issues, etc etc.
Handy related mysql tip:
On almost all servers, mysql also needs to know the tz info.
Basically the solution is, on the shell
sudo mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql mysql
.. google more about it.
I solved this using moment.js (http://momentjs.com/docs/)
var moment = require('moment');
var offset = moment().utcOffset();
console.log(''.concat(offset < 0 ? "-" : "+",moment(''.concat(Math.abs(offset/60),Math.abs(offset%60) < 10 ? "0" : "",Math.abs(offset%60)),"hmm").format("HH:mm")));
------Edited--------
I found a better solution using moment.js. Just use moment().format('Z')
which gives the output :
+05:30

how to get local timezone on azure service

I have a service running on azure cloud. This service runs in every 1 min and picks some files from ftp server. These files have Datetime fields and not datetimeoffset, which when read by service become UTC dates. These FTp servers are in different timezone.
For example one of the ftp is in GMT timezone. Say file has date 12/5/2015 time 12:15. This is read by service as UTC(because no timezone received) and stored in database as 12/5/2015: 12:15:00 +0:00, while it should be
12/5/2015: 11:15:00 +0:00.
I still want to save date in database as UTC, need a way to get these ftp timezones, so I can parse date correctly.
The problem is we can't make any changes in file.
Is there any way cloud sevice can get timezone for these FTP?
There's nothing Azure specific here for what you want, but you can roll your own solution.
You'd have to do some fancy stuff to guess the timezone of an FTP server, which would involve doing a DNS lookup of the server to figure out it's IP address, mapping that IP address to a city, and looking up the city's Time Zone. You could do that but it would be error prone.
There's an easier and more reliable option. It sounds like you your list of FTP servers is fairly static. You can just create a lookup table that says which timezone each FTP server is in, and use that table to figure out which timezone offset you should use.
Best practice: Server-side code should never depend on the time zone or culture settings of the server that is hosting the code. Instead, these concerns should be addressed in the code itself.
For example, assuming your service is written in C# / .NET, you might have code like this:
string s = "12/5/2015 12:15 PM"; // from the file
DateTime dt = DateTime.Parse(s);
DateTime utc = dt.ToUniversalTime();
The above code relies on the server's local time zone during the ToUniversalTime function. It also relies on the server's culture during the Parse function.
Instead, you should have knowledge of the time zone and culture of the input file. For example:
string s = "12/5/2015 12:15 PM"; // from the file
DateTime dt = DateTime.ParseExact(s, "M/d/yyyy h:mm tt", CultureInfo.InvariantCulture);
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time");
DateTime utc = TimeZoneInfo.ConvertTimeToUtc(dt, tz);
This code supplies the CET/CEST time zone, and also provides an exact input format using the invariant culture.
Late post, but thought I would post my solution to help anyone else:
TimeZone localZone = TimeZone.CurrentTimeZone;
var cetZone = TimeZoneInfo.FindSystemTimeZoneById(localZone.StandardName);
var cetTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetZone);
DateCreated = Convert.ToDateTime(cetTime.ToString());
In my instance, the localZone.StandardName gives me "South African Standard Time", which I believe is GMT+2.
Hope this helps someone else out!
Cheers

Google Tasks Migration to Exchange account

I have retrieved Tasks from my Gmail account using OAuth 2.0 Dot Net Google client library (https://developers.google.com/api-client-library/dotnet/apis/tasks/v1). When I save any of these tasks to my exchange account using Microsoft.Exchange.WebServices Dot Net library, the date of Task is adjusted automatically, although the time zone of Gmail account and exchange account are same i.e. Central Time (US & Canada). I want to prevent this automatically adjustment in Task date.
Can any one help?
Make sure you set the time zone on the ExchangeService object to the user's time zone. https://msdn.microsoft.com/EN-US/library/office/dn789029(v=exchg.150).aspx
I have solved the problem by using Calendar time zone. Basically, Google Calendar has time zone information. I retrieved time zone information from primary calendar and then before saving Task to Exchange account, I converted due date to UTC with following C# code
if (task.Due.Value.Kind == DateTimeKind.Local)
{
dueDateUTC = task.Due.Value.ToUniversalTime();
unspecifiedKindDate = new DateTime(dueDateUTC.Year, dueDateUTC.Month, dueDateUTC.Day);
dueDateUTC = TimeZoneInfo.ConvertTime(unspecifiedKindDate, Utility.OlsonTimeZoneToTimeZoneInfo(timezone), TimeZoneInfo.Utc);
}
This code first of all find out that whether Task due date is in local time zone or not. If it is in local time zone then due date is converted into UTC. After converting into UTC, a unspecified kind datetime object is created through following code
unspecifiedKindDate = new DateTime(dueDateUTC.Year, dueDateUTC.Month, dueDateUTC.Day);
This unspecified kind datetime is then again converted to UTC with the help of following code
dueDateUTC = TimeZoneInfo.ConvertTime(unspecifiedKindDate, Utility.OlsonTimeZoneToTimeZoneInfo(timezone), TimeZoneInfo.Utc);
Now this "dueDateUTC" object is used to save Task information into Exchange account. On saving Task, Exchange server automatically converts dueDateUTC to mailbox time zone and this was desired. :)

Resources