Turn off timezone DST adjustment in VB.NET? - asp.net

fellow programmers. Recently i got a problem when the DST applied to my asp.net application.
Originally, i got my datetime converter as follow:
Private Function ConvertTimezone(convertDatetime As DateTime, zoneID As String) As DateTime
Dim timeZoneInfo As TimeZoneInfo = System.TimeZoneInfo.FindSystemTimeZoneById(zoneID)
Dim dataTimeByZoneId As DateTime = System.TimeZoneInfo.ConvertTime(convertDatetime, System.TimeZoneInfo.Local, timeZoneInfo)
Return dataTimeByZoneId
End Function
Which is running smoothly as i am expected. However, when daylight saving started, all stuff seems to went to the wrong way AS I LIST THE OPTION TO SELECT AS UTC - 12 TO UTC + 12 by getting the standard time and convert it using the above code.
For example, the problem i am facing is the shift of hours, before DST, My UTC - 5 is from Atlantic standard time ,but after DST it returns UTC - 4 now as .NET CONVERT IT BY ITSELF. The dropdown has gone wrong since then.
Is there anyway to turn the DST adjustment off? or any other work around can complement the offset? (No other library is allowed ,sorry fellows..)

I worked it around by parsing the UTC + x value where x is the offset
Private Function ConvertTimezone(convertDatetime As DateTime, zoneID As String) As DateTime
Dim desttimeZoneInfo As TimeZoneInfo
Dim dataTimeByZoneId As DateTime
If Not zoneID.Contains("GMT") Then
desttimeZoneInfo = System.TimeZoneInfo.FindSystemTimeZoneById(zoneID)
dataTimeByZoneId = System.TimeZoneInfo.ConvertTime(convertDatetime, System.TimeZoneInfo.Local, desttimeZoneInfo)
Else
dataTimeByZoneId = System.TimeZoneInfo.ConvertTimeToUtc(convertDatetime, System.TimeZoneInfo.Local)
dataTimeByZoneId = dataTimeByZoneId.AddHours(Double.Parse(zoneID.Substring(3)))
End If
Return dataTimeByZoneId
End Function

Related

Java 8, time is not being converted

I'm using Hibernate 5 & MySQL.
This is what is getting saved into the database: 2018-03-11 06:26:47.336 I don't think this is 24 hour format, but then how do I see AM/PM? And how do I save the time in 24 hour format?
Running SELECT ##global.time_zone; in MySQL shows me: +00:00 So I think I'm set for accepting UTC time? This is how I set my pojo's field for setting time:
Clock clock = Clock.systemUTC();
LocalDateTime userCreated = LocalDateTime.now(clock);
It accepts LocalDateTime. But what I get back from database when I query is: u1.getUserCreated(): 2018-03-11T01:26:47.336 And when I try to convert the time into zone specific, I get the below:
ZonedDateTime z1 = ZonedDateTime.of(u1.getUserCreated(), ZoneId.of("America/New_York"));
System.out.println("z1: " + z1);
// z1: 2018-03-11T01:26:47.336-05:00[America/New_York]
But it really should be: 9:26:47.336 PM (21:26:47.336) As you can see on this site: http://www.timebie.com/std/utc.php
You're just not converting correctly. Your LocalDateTime represents the wall-clock time in the UTC time zone. Not in the New York time zone. So yo need to transform it to a ZonedDateTime in UTC::
ZonedDateTime utcDateTime = u1.getUserCreated().atZone(ZoneOffset.UTC);
Then, if you want to get a ZonedDateTime for the same instant, but in the New York timezone, then, well, just do that:
ZonedDateTime newYorkDateTime = utcDateTime.withZoneSameInstant(ZoneId.of("America/New_York"));

How to check cutoff time before or after the current time instance?

Currently i am working with shipping condition. in this i will get cut off time against the company like (05.00 PM) .
Now i want to compare above time with current time whether it is before cut off time or after cut off time?
I have gone through all the link i can see only example with date. i could not find anything with time.
Please let me know or give a some clue so that i will sorted out.
This is What i have tried so far
String todayDate=LocalDate.now().toString("dd.MM.yyyy");
String s=todayDate+cutOffTime;//cutOffTime will get from DB
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd.MM.yyyy HH:mm a");
LocalDate despatchDate=LocalDate.now();
try {
Date cutoffDate=simpleDateFormat.parse(s);
if (cutoffDate.after(Calendar.getInstance().getTime())){
despatchDate.plusDays(1);
}
} catch (ParseException e) {
e.printStackTrace();
}
Java 8 date/time api
LocalDateTime currentDateTime = LocalDateTime.now();
LocalDate currentDate = LocalDate.now();
String cutOff = "05:00 AM";
DateTimeFormatter timeParser = DateTimeFormatter.ofPattern("hh:mm a");
LocalTime cutOffTime = timeParser.parse(cutOff, LocalTime::from);
LocalDateTime cutOffDateTime = LocalDateTime.of(currentDate, cutOffTime);
//After
cutOffDateTime.isAfter(currentDateTime);
//Before
cutOffDateTime.isBefore(currentDateTime);
//Compare
cutOffDateTime.compareTo(currentDateTime);
Time Zone
The Answer by Shiv V is going in the right direction, but is not spot-on. The answer ignores the crucial issue of time zone. The Local… types intentionally lose and ignore time zone information, that is their purpose. But we rarely want to lose time zone info.
Determining the date and time-of-day depends on time zone. For any given moment, the date and time can vary around the globe. A few minutes after midnight in Paris is a new day while still “yesterday” in Montréal.
The Instant class defines a moment on the timeline in UTC with a resolution of nanoseconds.
Instant now = Instant.now();
If the desired deadline is “5 PM tomorrow”, you must specify the time zone as the context. Apply a ZoneId to an Instant to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
ZonedDateTime zdtTomorrow = zdt.plusDays( 1 );
Now adjust to 5 PM.
LocalTime timeOfDayWhenDue = LocalTime.of( 5 , 0 );
ZonedDateTime zdtDeadline = zdtTomorrow.with( timeOfDayWhenDue );
You can compare using the isEqual, isBefore, and isAfter methods.
ZonedDateTime now = ZonedDateTime.now( zoneId );
boolean overdue = now.isAfter( zdtDeadline );
You could also convert the zoned date-times back to UTC. The ZonedDateTime objects and their respective Instant objects represent the same simultaneous moment on the timeline (same moment in history), but seen from the viewpoint of different time zones (America/Montreal versus UTC).
Instant instantDeadline = zdtDeadline.toInstant();
Instant instantNow = now.toInstant();
boolean overdue = instantNow.isAfter( instantDeadline );
If you want to communicate the deadline to a customer in India, adjust into another time zone. The date-time value will represent the same moment on the timeline but will display with a wall-clock time that has meaning for that customer.
ZoneId zoneId_Kolkata = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdtDeadline_Kolkata = zdtDeadline.withZoneSameInstant( zoneId_Kolkata );
If you do not specify time zones, the JVM’s current default time zone is applied implicitly, silently. Not good. For one thing, implicit assumptions make your code easy-to-misunderstand and makes bugs more difficult to pinpoint. Worse, the default can change at any time, when you deploy to a different computer, or even during runtime at any moment of your app’s execution! Better to always specify the desired/expected time zone. By the way, same goes for Locale.

Date field changing from UK to US culture upon SaveChanges (EF6.1)

I am using a custom overloaded SaveChanges to implement some auditing functionality. The functionality works perfectly with the exception of some unexpected behaviour in relation to dates. In this example I'm changing a date field value from 1st May 2014 to 2nd May 2014:
A change is made to the database here:
Public Function UpdateTask(request As DataSourceRequest, ThisTask As JobTasksVM) As JsonResult
Dim cu As ApplicationUser = GetCurrentUser()
Dim CurrentTask = db.events.Find(ThisTask.id)
CurrentTask.start_date = ThisTask.start '<--- 2/5/2014 (ie 2nd May 2014), was previously 1/5/2014
CurrentTask.date = ThisTask.end
CurrentTask.task_name = ThisTask.Title
db.SaveChanges(cu.Employee_id)
End Function
This is intercepted by my custom SaveChanges:
Public Overloads Function SaveChanges(userID As Integer) As Integer
For Each entry As dbentityentry In Me.ChangeTracker.Entries().Where(Function(e) e.State <> EntityState.Unchanged)
Dim startOriginal As DateTime = entry.OriginalValues.Item("start_date")
Dim StartCurrent As DateTime = entry.CurrentValues.Item("start_date")
etc....
The bizarre thing is that whilst CurrentTask.start_date that is committed clearly shows the correct (UK) date of 2/5/2014 (2nd May 2014) the values within the overloaded SaveChanges are:
startOriginal: 5/1/2014 (ie 5th Jan 2014) <-- seems to have changed to US culture
startCurrent: 2/5/2014 (ie 2nd May 2014) <---as expected
I need to use the Original values in my audit functionality so this is causing a problem. I have also tried:
entry.CurrentValues.SetValues(entry.GetDatabaseValues)
But this also loads in the erroneous (ie US format 5/1/2014) into the start_date field.
I've checked all the culture settings on the system and they are all correctly English-UK. This behaviour seems fundamentally inconsistent - am I missing something?!
Thanks
DateTime types do not have a format, they are simply a value (number of ticks since 1/1/0001).
You did not say where you are seeing the "wrong" format, whether ToString() output or in intellisense. If you use ToString to the Output window, you should see the UK format since ToString will use/respect the local culture setting of the computer.
Intellisense is culture agnostic and tries to use an unambiguous format: MM/dd/yyyy. This is the same "format" or order you have to use when creating a DateTime var from a literal:
Dim dt As DateTime = #1/5/2014# ' e.g. MM/dd/yyyy
' same as:
Dim dt As New DateTime(1, 5, 2014) ' mm, dd, yyyy
This is InvariantCulture (not US). When you hold the mouse over the var, the VB IDE will use the same order. It tries to make clear it is using the required literal/InvariantCulture format by displaying it with the hashes: #1/5/2014#.
Dim dt As DateTime = #2/11/2011#
Console.WriteLine(dt.ToString)
In the US, 2/11/2011 will display based on the culture
In the UK, it will be 11/2/2011
Intellisense will be #2/11/2011#

how to display current time with chosen timezone?

how to display current time with chosen timezone instead of server TZ? (VB)
to use any TZ; simply use this row to add hours:
anytime = DateAdd("H", HOUR_DIFFERENCE, Now())
Public Declare Function GetTimeZoneInformation Lib "kernel32" Alias
"GetTimeZoneInformation" (lpTimeZoneInformation As
TIME_ZONE_INFORMATION) As Long
Public Type TIME_ZONE_INFORMATION
Bias As Long
StandardName(32) As Integer
StandardDate As SYSTEMTIME
StandardBias As Long
DaylightName(32) As Integer
DaylightDate As SYSTEMTIME
DaylightBias As Long
End Type
GMT = systemtime + bias

.NET 2.0 DateTime UTC conversion

Why does the ToUniversalTime function have no effect here;
DateTime dt = new DateTime(2009,3,24,1,0,0,DateTimeKind.Local);
dt = dt.ToUniversalTime(); // convert BST to UTC ?
dt.ToString();
"24/03/2009 01:00:00" ... wrong?
Is the same as..
DateTime dt = new DateTime(2009,3,24,1,0,0,DateTimeKind.Utc);
dt = dt.ToUniversalTime(); // nothing to do, already utc
dt.ToString();
"24/03/2009 01:00:00" ... correct.
I expected there to be an adjustment to the ToString() value of the first example, where by the DateTime specified as Local would result in a corresponding TimeZone calculation upon the call to ToUniversalTime() and the time in the UK should have resulted in
"24/03/2009 00:00:00" as UTC.
However it appears like the specifying of the DateTimeKind in this way renders ToUniversalTime or ToLocalTime unable to make any calculation.
Are you in the UK by any chance? Although we are now in daylight saving time, the date you specify in your code is before this switched over, so local and UTC time in the UK are the same. If you specify April as your month, then you will see a one hour difference.
Cheers David M.
Not had my breakfast. Indeed, when I repeat the test with dates that elapse the BST summer-time threshold, the behaviour is of course correct.
DateTime dt = new DateTime(2009,4,24,1,0,0,DateTimeKind.Local);
dt = dt.ToUniversalTime(); // convert BST to UTC ?
dt.ToString(); // "24/04/2009 00:00:00" ... correct
And to confirm, the ToString() method appears to output based on the Kind property.

Resources