Getting the start of a day for a specific date in JavaScript while considering the timezone

I'm having trouble determining the start of a day while factoring in timezones using javascript. Consider this example:

   var raw_time = new Date(this.created_at);
   var offset_time = new Date(raw_hour.getTime() + time_zone_offset_in_ms);

   // This resets timezone to server timezone
   var offset_day = new Date(offset_time.setHours(0,0,0,0))
   // always returns 2011-12-08 05:00:00 UTC, no matter what the offset was!

   // This has the same issue:
   var another_approach_offset_day = new Date(offset_time.getFullYear(),offset_time.getMonth(),offset_time.getHours())

When I provide a Pacific Timezone offset, I expect to receive: 2011-12-08 08:00:00 UTC and so forth.

What is the correct way to achieve this?

I believe part of the problem lies in the fact that the setHours method sets the hour (from 0 to 23) based on local time.

Please note that I am utilizing javascript embedded in mongo, restricting me from employing any additional libraries.

Thank you!


Wow, this was quite a challenge for me, but I managed to come up with a final solution. The key was realizing I needed to use setHours or SetUTCHours to find the start of a day - my only options being system time and UTC. So, I obtain the beginning of a UTC day and then adjust for the offset!

// Objective: determine the start of a day given a time and timezone
function(timestamp, selected_timezone_offset) {
  var raw_time = new Date(timestamp)
  var offset_time = new Date(raw_time.getTime() + selected_timezone_offset);
  offset_time.setUTCHours(0,0,0,0);
  var beginning_of_day = new Date(offset_time.getTime() - selected_timezone_offset);
  return beginning_of_day;
}

Answer №1

When working with dates in JavaScript, it's important to remember that all dates are stored as UTC. This means that the serial number returned by date.valueOf() represents the number of milliseconds since 1970-01-01 00:00:00 UTC. However, when you view a date using methods like .toString() or .getHours(), you actually see the value in local time - the time of the system running the script. To retrieve the value in UTC, you can use methods such as .toUTCString() or .getUTCHours().

While you can't directly obtain a date in any arbitrary timezone (it's either UTC or local), you can still display a string representation of a date in your desired timezone by adjusting for the UTC offset. The simplest way to do this is by subtracting the UTC offset from the date and then calling .getUTCHours() or .toUTCString():

var d = new Date();
d.setMinutes(d.getMinutes() - 480); // adjust for pacific standard time
d.toUTCString(); // returns "Fri, 9 Dec 2011 12:56:53 UTC"

If you want to replace the "UTC" at the end with something like "PST", you can simply perform a string substitution:

d.toUTCString().replace(/UTC$/, "PST");

Edit: When dealing with timezones crossing date boundaries, you need not worry. If you provide setHours() with a negative value, it will correctly handle the subtraction of hours from midnight on the previous day. For example:

var d = new Date(2011, 11, 10, 15); // Represents Dec 10, 2011 at 3pm local time
d.setHours(-1);                     // Represents Dec 9, 2011 at 11pm local time
d.setHours(-24);                    // Represents Dec 8, 2011 at 12am local time
d.setHours(52);                     // Represents Dec 10, 2011 at 4am local time

Answer №2

Have you considered the source of the time_zone_offset_in_ms variable you are using? It might be unreliable; instead, you could utilize Date's getTimezoneOffset() method for accuracy. You can find an example at this URL:

http://www.example.com/jsref/getTimezoneOffset

Answer №3

To retrieve the date from a varying date string, use the code snippet below:

let selectedDate = new Date(this.$picker.data('date'));
let todayDate = new Date();
todayDate.setHours(0, -selectedDate.getTimezoneOffset(), 0, 0);

(inspired by a previous project's implementation)

Answer №4

let currentDate = new Date();
let startOfDay = new Date(currentDate.getTime() - currentDate.getTime() % 86400000);

This code snippet will generate the start of the current day.

Answer №5

If you want to work with date and time in different timezones, one useful tool is the Intl.DateTimeFormat feature. Another option is to look at how luxon library deals with timezones.

The following code snippet demonstrates how you can convert any date with any timezone to its beginning or end of the day:

const beginingOfDay = (options = {}) => {
  const { date = new Date(), timeZone } = options;
  const parts = Intl.DateTimeFormat("en-US", {
    timeZone,
    hourCycle: "h23",
    hour: "numeric",
    minute: "numeric",
    second: "numeric",
  }).formatToParts(date);
  const hour = parseInt(parts.find((i) => i.type === "hour").value);
  const minute = parseInt(parts.find((i) => i.type === "minute").value);
  const second = parseInt(parts.find((i) => i.type === "second").value);
  return new Date(
    1000 *
      Math.floor(
        (date - hour * 3600000 - minute * 60000 - second * 1000) / 1000
      )
  );
};

const endOfDay = (...args) =>
  new Date(beginingOfDay(...args).getTime() + 86399999);

const beginingOfYear = () => {};

console.log(beginingOfDay({ timeZone: "GMT" }));
console.log(endOfDay({ timeZone: "GMT" }));
console.log(beginingOfDay({ timeZone: "Asia/Tokyo" }));
console.log(endOfDay({ timeZone: "Asia/Tokyo" }));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unusual behavior of the `map` function in Firefox's JavaScript

Here's an interesting observation regarding the behavior of the map function in Firefox. In a particular error scenario on a web application, when Firebug pauses at the error, entering the following code into the Firebug console: ["a", "b", "c", "d" ...

Guide to integrating Google Maps JS API into a React application without relying on third-party libraries

I'm currently grappling with the concept of integrating external APIs in React and am interested in using Google Maps' API to showcase a map within a child component. My goal is to gain insight into how this can be done without relying on any ext ...

Tips for integrating H4 - H6 using a text editor in DNN7

It is essential for my client to have access to at least H4. Although I can add H4 to the ApplyClass menu in the text editor, it only applies a <span class="h4"> Sample </span> tag within the paragraph itself. Unfortunately, this method does ...

A Promise-based value returned by a Typescript decorator with universal methods

I am currently working on creating a method decorator that can be applied to both prototype and instance methods. Referenced from: Typescript decorators not working with arrow functions In the code provided below, the instanceMethod() is returning a Prom ...

Troubleshooting JavaScript in Internet Explorer 9

Currently, I am encountering an issue while attempting to debug JavaScript .js files in my Solution using Visual Studio 2010 and IE 9. Despite placing breakpoints in the files, I am unable to debug successfully. I have attempted various troubleshooting ste ...

How many server queries does a single web application require?

As someone new to web app development, my main goal is to optimize speed as much as possible. I am faced with two options: The first option is to fetch data from the database individually every time a refresh is needed in the app. Alternatively, I c ...

Acquire the content of an interactive website with Python without using the onclick event

I am looking to extract the content of a dynamically generated website after clicking on a specific link. The link is structured as follows: <a onclick="function(); return false" href="#">Link</a> This setup prevents me from directly accessin ...

Name or Title of a Polygon/Polyhedron Using Three.js

My page contains a sample code that successfully retrieves the name of an object when a user clicks on it. However, the code works well with cubes and spheres but fails with polygons. To see how the clicks respond, you can check the console logs. What shou ...

"Executing a query on Angular Firestore using the where clause fetches all documents from the

I am encountering a perplexing issue with my angular app that is connected to Firestore. Despite following the documentation closely, when I query for documents in a collection based on a specific condition, the array returned contains every single documen ...

Ensure to preselect the radio button based on the Day's value

I have set up my Radio buttons with corresponding content to be displayed when clicked. I want to automatically pre-select the tab button based on the current day. For example, if today is Sunday, the page should load showing the contents for Sunday. If i ...

Bootstrap Tags Input - the tagsinput does not clear values when removed

I am attempting to manually remove the input value from bootstrap-tags-input when the x button is clicked, but the values are not changing in either the array or the inputs. This is the code I have tried: $('input').tagsinput({ allowDuplica ...

Employ an asynchronous immediately-invoked function expression within the callback

Can an asynchronous IIFE be used inside the callback function to avoid the error message "Promise returned in function argument where a void return was expected"? You can find an example here. signIn(email: string, password: string, course?: ICourse): ...

Contrast between pm.response.json() and parsing the responseBody using JSON.parse()

Can you explain the key distinction between const json_response = pm.response.json() and json_response = JSON.parse(responseBody) ...

Error Alert: The combination of React and Redux-router is causing an unexpected issue. The reducer is expected to be a

Whenever I make a coding mistake and encounter a runtime error, the error reporting is not very helpful. For example, when I mistakenly typed Date() instead of new Date(), the error message I received was... Uncaught Error: Expected the reducer to be a fu ...

Securing your MongoDB 3.2 Database with User Authentication

Following the instructions in this tutorial on setting up authentication with Mongo DB, and also referring to this other guide to configure a user as an administrator. After executing mongo, then use admin, followed by show users, the details displayed ar ...

"Implementing @Indexed in Spring Data Mongo results in the creation of redundant indexes

When utilizing the @Indexed annotation in conjunction with Spring Data Mongo and following it up with @Document at a class level, I've observed from the logs that a new index is created each time the connection to the Mongo DB is established. Is this ...

Ways to prevent negative values from appearing in the text field

Check out this code snippet on Fiddle. I need help with a text field that should only display positive values. If the input is negative, I want it to be stored in ng-model but not shown in the textbox. function LoginController($scope) { $scope.number = ...

Unable to focus on the same DOM element multiple times - Vue.js

Apologies for any syntax errors, although the code is functioning perfectly. There may have been a mistake during the copying process. Situation: I am facing an issue with a component called 'dropdown', which is repeated three times using v-for= ...

Attaching a click event to an input field

Seeking to serve html files from the server without relying on template engines. Below is the script used to start the server. // script.js const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(expr ...

MongoDB refusing to process delete command

USER: const handleDelete = (id) => { console.log(id); axios.delete(`http://localhost:3001/delete`, {id}) .then(res => console.log(err)}) .catch(err => console.log(err)) } SHOWS ID CORRECTLY IN CONSOLE: vv17OZpdGkMwNEv0 SER ...