next day of a date in javascript with default js functions - javascript

Is it possible to get next date of a given date in "yyyymmdd" format with default java script or jquery functions?

As you've specified jQuery UI you can use its built-in date formatter to get the required output.
The use of the regexp and new Date shown below is to guarantee that the vagaries of date parsing don't affect the result.
function getTomorrow(dateStr) {
var ymd = dateStr.match(/^(\d{4})(\d{2})(\d{2})$/);
if (ymd) {
var date = new Date(ymd[1], ymd[2] - 1, ymd[3]);
date.setDate(date.getDate() + 1);
return $.datepicker.formatDate('yymmdd', date);
} else { // parse error
return null;
}
}
Demo at http://jsfiddle.net/alnitak/R8awH/

There seems to be a bit of confusion here.
At the heart of a javascript Date object is the milliseconds since 1970-01-01 00:00:00 UTC. That last bit is very important.
If you create a date by specifying the parts, e.g. for 2 September 2012 (note month number):
new Date(2012, 8, 2);
then a date object is created for midnight at the start of the date in the local time zone of the host, i.e. 2012-09-02T00:00:00 in the local timezone. However, if you specify a time since epoch, e.g.
new Date(1346544000000) // 2012-09-02T00:00:00Z
then the date is created at that time UTC, so it will show a different local time in different timezones that represents the same time UTC. So if the time is 2012-09-02T00:00:00Z, then in a timezone ten hours ahead of GMT (GMT+10) it will be:
2012-09-02T10:00:00+1000
If the timezone is six hours behind GMT (GMT-06) it will be:
2012-09-01T18:00:00-0600
and so on.

Construct the date object, and set the date plus 1.
var dateStr = "20120902";
var d = new Date(dateStr.replace(/(\d{4})(\d{2})(\d{2})/, '$1/$2/$3'));
d.setDate(d.getDate() + 1);
console.log(d);

Here is your code:
function getnextDay(prevDate) {
var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
prevDate = prevDate.toString();
var formatteDate = prevDate.substr(0, 4) + ',' + prevDate.substr(4, 2) + ',' + prevDate.substr(6, 2);
formatteDate = new Date(formatteDate);
document.write(weekday[formatteDate.getDay() + 1])
}
getnextDay(19890831)​​
and
FIDDLE

Its pretty straight forward.
var today = new Date();
var date = new Date(today.getFullYear(),today.getMonth(),today.getDate()+1);
Use moment.js if you extensively use date functionalities.
For just getting the next day, this would suffice.

yes
It is pretty much easy with javaScript as follow:
today = new Date().getTime();
tomorrow = today + 24*60*60*1000;
parsed_tomorrow = new Date(tomorrow);

Related

How can I get the timestamp in javascript from a string including the timezone db name

I got the following string: "2022/05/01 03:10:00" and I need to create a Date object forcing it to use Chile's UTC offset.
The problem is that because of Daylight saving time (DST) the offset changes twice a year.
How can get that Date object, for example, using the "America/Santiago" TZ db name?
Something like:
new Date("2022/05/01 03:10:00" + getUtcOffset("America/Santiago")).
function getUtcOffset(tzDbName) {
..
}
Returns -3 or -4, depending the time in the year.
EDIT:
I ended using a nice trick for determining if DST was on or off.
reference
const dst = hasDST(new Date(strDate));
function hasDST(date = new Date()) {
const january = new Date(date.getFullYear(), 0, 1).getTimezoneOffset();
const july = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
return Math.max(january, july) !== date.getTimezoneOffset();
}
Then I could create the date with the correct timezone depending on that variable.
if (dst) {
let d = new Date(strDate + " GMT-0300");
return d;
} else {
let d = new Date(strDate + " GMT-0400");
return d;
}
Thanks everyone!
EDIT2:
I finally found a very nice library that does exactly what I was looking for:
https://date-fns.org/v2.28.0/docs/Time-Zones#date-fns-tz
const { zonedTimeToUtc, utcToZonedTime, format } = require('date-fns-tz')
const utcDate = zonedTimeToUtc('2022-05-05 18:05', 'America/Santiago')
This has been discussed before here.
Haven't tested it, but it appears that the simplest solution is:
// Example for Indian time
let indianTime = new Date().toLocaleTimeString("en-US",
{timeZone:'Asia/Kolkata',timestyle:'full',hourCycle:'h24'})
console.log(indianTime)
You can check the link for more complex answers and libraries
Generals notes
To get the time zone name use:
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)
To get the difference from UTC (in minutes) use:
var offset = new Date().getTimezoneOffset();
console.log(offset);
// if offset equals -60 then the time zone offset is UTC+01

Error incrementing days to a specific date

I'm trying to increment one day to a given date. My code, inspired by this answer, looks like:
var date = getDateFromUIControl();
var backupDate = new Date();
backupDate.setDate(date.getDate() + 1);
However, I'm seeing a strange behaviour. Today is December 5th, 2019. If the user selects January 1, 2020 (stored in date variable), then backupDate ends up being January 2nd, 2019, instead of 2020. What is wrong with this code? How should I go about incrementing the date, if what I'm doing is wrong?
Note: because of whatever policies my company has, I can't use any JavaScript library other than jQuery.
new Date() returns the current Date(example: 05/12/2019). You are just changing the date alone in current date. Still the year is 2019.
it should be like,
date.setDate(date.getDate() + 1);
if you can't change the original date object, then it can be done like this,
var changedDate = new Date(date);
changedDate.setDate(changedDate.getDate() + 1);
var date = getDateFromUIControl();
var backupDate = new Date();
backupDate.setDate(new Date(date).getDate() + 1);
nextDay is one day after date:
var date = getDateFromUIControl();
var nextDay = new Date(date.getYear(), date.getMonth(), date.getDate()+1);
Also you don't need to worry about overflowing d.getDate()+1 (e.g. 31+1) - the Date constructor is smart enough to go into the next month.

Create a Date object with CET timezone

To create Date object in UTC, we would write
new Date(Date.UTC(2012,02,30));
Without Date.UTC, it takes the locale and creates the Date object. If I have to create a Date object for CET running the program in some part of the world, how would I do it?
You don't create a JavaScript Date object "in" any specific timezone. JavaScript Date objects always work from a milliseconds-since-the-Epoch UTC value. They have methods that apply the local timezone offset and rules (getHours as opposed to getUTCHours), but only the local timezone. You can't set the timezone the Date object uses for its "local" methods.
What you're doing with Date.UTC (correctly, other than the leading 0 on 02) is just initializing the object with the appropriate milliseconds-since-the-Epoch value for that date/time (March 30th at midnight) in UTC, whereas new Date(2012, 2, 30) would have interpreted it as March 30th at midnight local time. There is no difference in the Date object other than the datetime it was initialized with.
If you need a timezone other than local, all you can do is use the UTC version of Date's functions and apply your own offset and rules for the timezone you want to use, which is non-trivial. (The offset is trivial; the rules tend not to be.)
If you go looking, you can find Node modules that handle timezones for you. A quick search for "node timezone" just now gave me timezone as the first hit. It also gave me links to this SO question, this SO question, and this list of timezone modules for Node.
function getCETorCESTDate() {
var localDate = new Date();
var utcOffset = localDate.getTimezoneOffset();
var cetOffset = utcOffset + 60;
var cestOffset = utcOffset + 120;
var cetOffsetInMilliseconds = cetOffset * 60 * 1000;
var cestOffsetInMilliseconds = cestOffset * 60 * 1000;
var cestDateStart = new Date();
var cestDateFinish = new Date();
var localDateTime = localDate.getTime();
var cestDateStartTime;
var cestDateFinishTime;
var result;
cestDateStart.setTime(Date.parse('29 March ' + localDate.getFullYear() + ' 02:00:00 GMT+0100'));
cestDateFinish.setTime(Date.parse('25 October ' + localDate.getFullYear() + ' 03:00:00 GMT+0200'));
cestDateStartTime = cestDateStart.getTime();
cestDateFinishTime = cestDateFinish.getTime();
if(localDateTime >= cestDateStartTime && localDateTime <= cestDateFinishTime) {
result = new Date(localDateTime + cestOffsetInMilliseconds);
} else {
result = new Date(localDateTime + cetOffsetInMilliseconds);
}
return result;
}

Get the most recently occurring Sunday

I need to display the current week in a calendar view, starting from Sunday.
What's the safest way to determine "last sunday" in Javascript?
I was calculating it using the following code:
Date.prototype.addDays = function(n) {
return new Date(this.getTime() + (24*60*60*1000)*n);
}
var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var lastSunday = today.addDays(0-today.getDay());
This code makes the assumption that every day consists of twenty four hours. This is correct, EXCEPT if it's a daylight savings crossover day, in which case the day could be twenty-three or twenty-five hours.
This week, In Sydney, Australia, we set our clocks forward an hour. As a result, my code calculates lastSunday as 23:00 on Saturday.
So what IS the safest and most efficient way to determine last Sunday?
To safely add exactly one day, use:
d.setDate(d.getDate() + 1);
which is daylight saving safe. To set a date object to the last Sunday:
function setToLastSunday(d) {
return d.setDate(d.getDate() - d.getDay());
}
Or to return a new Date object for last Sunday:
function getLastSunday(d) {
var t = new Date(d);
t.setDate(t.getDate() - t.getDay());
return t;
}
Edit
The original answer had an incorrect version adding time, that does add one day but not how the OP wants.
Try this jsfiddle
It uses only built in date methods
var now = new Date();
var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var lastSunday = new Date(today.setDate(today.getDate()-today.getDay()));
using date-fn library: previousSunday(date)
const now = new Date(); // the date to start counting from
previousSunday(now);
Docs: https://date-fns.org/v2.25.0/docs/previousSunday

How to the get the beginning of day of a date in javascript -- factoring in timezone

I am struggling to find out the beginning of day factoring in timezones in javascript. Consider the following:
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())
I expect when i pass a Pacific Timezone offset, to get: 2011-12-08 08:00:00 UTC and so on.
What is the correct way to achieve this?
I think that part of the issue is that setHours method sets the hour (from 0 to 23), according to local time.
Also note that I am using javascript embedded in mongo, so I am unable to use any additional libraries.
Thanks!
Jeez, so this was really hard for me, but here is the final solution that I came up with the following solution. The trick was I need to use setHours or SetUTCHours to get the beginning of a day -- the only choices I have are system time and UTC. So I get the beginning of a UTC day, then add back the offset!
// Goal is given a time and a timezone, find the beginning of day
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;
}
In JavaScript all dates are stored as UTC. That is, the serial number returned by date.valueOf() is the number of milliseconds since 1970-01-01 00:00:00 UTC. But, when you examine a date via .toString() or .getHours(), etc., you get the value in local time. That is, the local time of the system running the script. You can get the value in UTC with methods like .toUTCString() or .getUTCHours(), etc.
So, you can't get a date in an arbitrary timezone, it's all UTC (or local). But, of course, you can get a string representation of a date in whatever timezone you like if you know the UTC offset. The easiest way would be to subtract the UTC offset from the date and call .getUTCHours() or .toUTCString() or whatever you need:
var d = new Date();
d.setMinutes(d.getMinutes() - 480); // get pacific standard time
d.toUTCString(); // returns "Fri, 9 Dec 2011 12:56:53 UTC"
Of course, you'll need to ignore that "UTC" at the end if you use .toUTCString(). You could just go:
d.toUTCString().replace(/UTC$/, "PST");
Edit: Don't worry about when timezones overlap date boundaries. If you pass setHours() a negative number, it will subtract those hours from midnight yesterday. Eg:
var d = new Date(2011, 11, 10, 15); // d represents Dec 10, 2011 at 3pm local time
d.setHours(-1); // d represents Dec 9, 2011 at 11pm local time
d.setHours(-24); // d represents Dec 8, 2011 at 12am local time
d.setHours(52); // d represents Dec 10, 2011 at 4am local time
Where does the time_zone_offset_in_ms variable you use come from? Perhaps it is unreliable, and you should be using Date's getTimezoneOffset() method. There is an example at the following URL:
http://www.w3schools.com/jsref/jsref_getTimezoneOffset.asp
If you know the date from a different date string you can do the following:
var currentDate = new Date(this.$picker.data('date'));
var today = new Date();
today.setHours(0, -currentDate.getTimezoneOffset(), 0, 0);
(based on the codebase for a project I did)
var aDate = new Date();
var startOfTheDay = new Date(aDate.getTime() - aDate.getTime() % 86400000)
Will create the beginning of the day, of the day in question
You can make use of Intl.DateTimeFormat. This is also how luxon handles timezones.
The code below can convert any date with any timezone to its beginging/end of the time.
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" }));

Categories