Skip to content
Fix Code Error

Create a Date with a set timezone without using a string representation

March 13, 2021 by Code Error
Posted By: Dan

I have a web page with three dropdowns for day, month and year. If I use the JavaScript Date constructor that takes numbers, then I get a Date object for my current timezone:

new Date(xiYear, xiMonth, xiDate)

Give the correct date, but it thinks that date is GMT+01:00 due to daylight savings time.

The problem here is that I then pass this Date to an Ajax method and when the date is deserialised on the server it has been converted to GMT and so lost an hour which moves the day back by one.
Now I could just pass the day, month, and year individually into the Ajax method, but it seems that there ought to be a better way.

The accepted answer pointed me in the right direction, however just using setUTCHours() by itself changed:

Apr 5th 00:00 GMT+01:00 

to

Apr 4th 23:00 GMT+01:00

I then also had to set the UTC date, month and year to end up with

Apr 5th 01:00 GMT+01:00

which is what I wanted.

Solution

using .setUTCHours() it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.

You cannot set it using UTC in the constructor though, unless you specify a date-string.

Using new Date(Date.UTC(year, month, day, hour, minute, second)) you can create a Date-object from a specific UTC time.

Answered By: jishi

Related Articles

  • Does moment.js allow me to derive a timezone…
  • Generating a drop down list of timezones with PHP
  • Should MySQL have its timezone set to UTC?
  • Java string to date conversion
  • Confused about the Visitor Design Pattern
  • Can't find why this datetime test fails, in F#
  • How to solve Internal Server Error in Next.Js?
  • How to prevent scrolling the whole page?
  • Downloading jQuery UI CSS from Google's CDN
  • Meaning of @classmethod and @staticmethod for beginner?
  • How to auto insert the current user into my db when…
  • How to obtain the start time and end time of a day?
  • How do I get the current time zone of MySQL?
  • Is java.sql.Timestamp timezone specific?
  • Why does `this` inside filter() gets undefined in VueJS?
  • Filtering an object based on key, then constructing…
  • set variable with conditions in dart
  • How to get a time zone from a location using…
  • How to change TIMEZONE for a java.util.Calendar/Date
  • Getting the difference between two Dates…
  • How to split one list of dicts into two lists of…
  • What's the difference between Instant and LocalDateTime?
  • What does this symbol mean in JavaScript?
  • How to use Servlets and Ajax?
  • Process time data with adjustments for DST
  • Ember.Object computed property returning an object
  • How to store a datetime in MySQL with timezone info
  • jQuery Mobile: document ready vs. page events
  • Error: listen EADDRINUSE 127.0.0.1:3000
  • Polymer nested dom-repeat templates are not updating…
  • get UTC timestamp in python with datetime
  • Ukkonen's suffix tree algorithm in plain English
  • Binding ComboBox SelectedItem using MVVM
  • The definitive guide to form-based website authentication
  • How to get min max day in a week every month?
  • Enable and show only specific dates and today date…
  • Subtract three rows from an array in angular 7
  • Rails formatting date
  • How do I convert a date/time to epoch time (unix…
  • How to handle calendar TimeZones using Java?
  • Don't let the user select a past date?
  • How to select the first row of each group?
  • How can I check if a month has 31 days or not
  • Get current time in hours and minutes
  • How do I calculate the date in JavaScript three…
  • How to calculate the operability ratio per month on Python?
  • Is resource nesting the only way to enable multiple…
  • How to get year, month, day, hours, minutes, seconds…
  • Format date and time in a Windows batch script
  • Get the name of an object's type
  • How do I keep only the first map and when the game…
  • Data structure for maintaining tabular data in memory?
  • How to add "new" element/objects s to a list in javascript?
  • Three.js: Cannot display mesh created with texture array
  • How to convert a string to JSON object in PHP
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Creating list with the same number of values
  • How to calculate the difference between two dates using PHP?
  • Is there a way to loop through JSON data and display…
  • How to import Moment-Timezone with Aurelia/Typescript
  • Parse Javascript new Date().toString() in Swift
  • Convert Java Date to UTC String
  • How do I simplify Laravel query for date searching…
  • How do I return the response from an asynchronous call?
  • Force Java timezone as GMT/UTC
  • I'm unable to get the right timezone offset with daylight
  • Binding an ember model's date attribute to…
  • DatePicker onDateSet method not running
  • Why is it common to put CSRF prevention tokens in cookies?
  • python pandas extract year from datetime: df['year']…
  • C# "must declare a body because it is not marked…
  • NSDate get year/month/day
  • What is the copy-and-swap idiom?
  • How to get 2 digit year w/ Javascript?
  • SQL Server Group By Month
  • polymer 1.0 dom-repeat filter only runs once
  • Vue modules, moment-timezone - How to load…
  • Calendar.getInstance(TimeZone.getTimeZone("UTC")) is…
  • Javascript, Time and Date: Getting the current…
  • Need help cleaning up .htaccess
  • Usage of __slots__?
  • Calculating a number from items in an array then…
  • Tkinter Duration Timer—What method will allow this…
  • Vue js select element with v-model in scoped slot
  • How do i update a javascript variable as its value changes?
  • How can I convert a date to GMT?
  • postgres default timezone
  • commandButton/commandLink/ajax action/listener…
  • What is the optimal algorithm for the game 2048?
  • How to stop a command on only one server discord.py?
  • Multipart File Upload Using Spring Rest Template +…
  • How to get previous month and year relative to…
  • Using `date` command to get previous, current and next month
  • javax.faces.application.ViewExpiredException: View…
  • Python MYSQL update statement
  • Using one iron-ajax element for multiple requests
  • Convert Date/Time for given Timezone - java
  • Trimmed mean by group in R data.table
  • How to ignore user's time zone and force Date() use…
  • Disabling a button upon condition in Google App script

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Prevent body scrolling but allow overlay scrolling

Next Post:

Access denied for user ‘[email protected]’ (using password:NO)

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error