Edit JavaScript (Tomorrow's date) - javascript

I am trying to edit some JavaScript code which basically shows tomorrow's date. However for Friday and weekends (Friday, Saturday and Sunday) it should show the following Monday's date.
Here is the code I have:
var date = new Date(); // timezone
date.setDate(date.getDate() + 1); // move to tomorrow
date.setUTCHours(11,0,0,0); // set time using UTC(GMT) timezone
document.getElementById("next-shipment").textContent = date.toLocaleString();
JSFiddle
For example let say today is Tuesday, November 4, 2015. The javascript code should show "November 5, 2015"---> in this format.
On Friday, Saturday,and Sunday the code should show: Next Monday's date: November 9, 2015
The code should work all year around.

Try this:
var today = new Date(); // timezone
document.getElementById("result").innerHTML = "<br/>Today's next day is: " + FormatDate(GetNextDay(today));
function GetNextDay(date){
date.setDate(date.getDate() + 1); // move to next day.
switch(date.getDay()) {
case 0: //Sunday
case 6: //Saturday
date = GetNextDay(date);
}
return date;
}
function FormatDate(date){
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
return months[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear();
}
function TestDate(){
var date = new Date(document.getElementById("TestDate").value);
document.getElementById("result").innerHTML += "<br/>Selected day's next day is: " + FormatDate(GetNextDay(date));
}
<input type="text" id="TestDate" value="November 06, 2015" />
<input type="button" value="Get Next Day" onclick="TestDate();" />
<div id="result"></div>
The idea is fairly simple:
The first two lines and the TestDate() function at the end are only for testing and you don't need them in your code.
The job is mainly done by the GetNextDay() function. You give it a date and it calculates and give you back the next date (skipping the weekend). It does that in two steps:
1- First it adds one day to the given date date.setDate(date.getDate() + 1);.
2- It checks the day of the new date date.getDay(). If it is 6 or 0 (Saturday or Sunday) it calls itself again date = GetNextDay(date); which means it will add one more day to the date. This concept of a function calling itself is called "recursion" in programming. When it reaches Monday, it will stop calling itself and return the date.
The only way to calculate the next day properly is by adding one day to the date. This utilizes JavaScript's Date library which knows how to do the calculation. For example, it knows that adding one day to "November 30" is "December 1", NOT "November 31". If we try to do that manually by adding 1 to number of the day: 30 + 1 = 31, but "November 31" is not a valid date. To solve this issue, we will need to write a library similar to the one that JavaScript has. Obviously, this is like reinventing the wheel and there is no point in that.

The Date constructor also has a function called getDay() which returns a integer between 0 and 6 (0 = Sunday, 6 = Saturday). You can use this to detect Friday(0), Saturday(6), Sunday(0) and omit them.
Here is a demo that alerts you if it's the weekend:
var myDate = new Date();
myDate.setFullYear(2015);
myDate.setMonth(11);
myDate.setDate(6);
if(myDate.getDate() == 5 || myDate.getDay() == 6 || myDate.getDay() == 0) alert('Weekend!');
document.write(myDate);
To find the next day, pass the Date constructor a time & it will do the work for you. You will need to create an array however to format it in the way you want November, 5 2015.
JS:
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var tomDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var day = tomDate.getDate();
var month = monthNames[tomDate.getMonth()];
var year = tomDate.getFullYear()
var d = new Date();
var n = d.getDay();
if(n == 5){
var fromFri = n + 4;
document.write("<b>" + month + " " + fromFri + ", " + year + "</b>");
}else if (n == 6){
var fromSat = n + 3;
document.write("<b>" + month + " " + fromSat + ", " + year + "</b>");
}else if (n == 0) {
var fromSun = n + 2;
document.write("<b>" + month + " " + fromSun + ", " + year + "</b>");
}else{
document.write("<b>" + month + " " + day + ", " + year + "</b>");
}
Updated: CODEPEN DEMO

Related

Display all 12 months serially but starting from the current month

I am working on a requirement where I have 12 ion slides and the names of the slides are month names starting from the current month. For ex: If the current month is June, then the name of the first slide should start from June 2020 and go on till May 2021. Well I tried it but not able to achieve. Even if I handle the month, then I am not able to dynamically change the year after December. Here is my code:
my html file
<ion-toolbar class="toolbars" #ionDragFooter>
<ion-title class="ion-text-center">{{currValue}}</ion-title>
</ion-toolbar>
My .ts file
ngOnInit() {
swipeNext()
}
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
var d = new Date();
if(index == 1){
var curMn=monthNames[d.getMonth()]+ d.getFullYear();
console.log(curMn)
this.currValue=curMn;
}
else if(index == 2){
var curMn=monthNames[d.getMonth()+1]+ d.getFullYear();
this.currValue=curMn;
}
else if(index == 3){
var curMn=monthNames[d.getMonth()+2]+ d.getFullYear();
this.currValue=curMn;
}
and so on for all other month. I need to completely automate the month and year starting from the current month. May I know where I went wrong?
You can create a date, then increment the month by 1 eleven times to get 12 months of dates. The month name can be found using toLocaleString with appropriate options.
You need to be careful when incrementing months, e.g.
let d = new Date(2020,0,31); // 31 Jan 2020
d.setMonth(d.getMonth() + 1) // 31 Feb 2020 -> 2 Mar 2020
d.toDateString(); // Mon Mar 02 2020
So best to set the date to the 1st of the month initially:
// Optionally provide a date for the starting month
function getMonthNames(date = new Date()) {
// Copy input date so don't modify it
let d = new Date(+date);
// Set to 1st of month
d.setDate(1);
let result = [];
// Get 12 month names, starting with current month
for (let i=0; i<12; i++) {
result.push(d.toLocaleString('default',{month:'long'}));
d.setMonth(d.getMonth() + 1);
}
return result;
}
console.log(getMonthNames());
To properly change the date you have to increase the date by the amount of months in the date object (in your case d):
var d = new Date();
//REM: This will print out the next month, yet d still is unchanged
console.log(d.getMonth()+1);
console.log(d);
console.log('Month did not increase: ', d.getMonth());
//REM: You have to increase your date by one month in the date object
d.setMonth(d.getMonth() + 1);
console.log(d);
console.log('Month did increase: ', d.getMonth());
//REM: By which it will change the year for you, once it is time for it.
d.setMonth(d.getMonth() + 11); //REM: +1 from before
console.log(d);
console.log('Year did increase: ', d.getFullYear());
In your case that would be:
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var d = new Date();
d.setDate(1); //REM: To prevent month skipping.
for(var i=0; i<12; i++){
d.setMonth(d.getMonth() + 1);
console.log(monthNames[d.getMonth()], d.getFullYear())
};
Some further reading on the issue
This is what I came up with:
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
const today = new Date();
//gives you year
const year = today.getFullYear();
//gives you month as number/index;
const month = today.getMonth();
//stores sequenced month names
const sequencedNames = [];
//creates June 2020 through December 2020
for(let i = month; i < monthNames.length; i++) {
let monthName = monthNames[i];
sequencedNames.push(monthName + " " + year)
}
//creates January 2021 through May 2021
for(let i = 0; i < month; i++) {
let monthName = monthNames[i];
sequencedNames.push(monthName + " " + (year + 1))
}
console.log(sequencedNames)
Essentially 2 for loops, the first iterating from the current month to the end of the year, and then the second from the start of the year to the current month -- though adding 1 year.

I'd like to display a string with location, date & time (of a pre-set timezone) [duplicate]

This question already has answers here:
How to make a display of a clock synchronous with the real time
(3 answers)
How do I format a date in JavaScript?
(68 answers)
How to initialize a JavaScript Date to a particular time zone
(20 answers)
Closed 3 years ago.
What I'd like to achieve should look like this in the bottom corner. However, I'd like to set a timezone, e.g. New York (that's not a timezone I know lol, but you understand) and it should display 'New York April 1st 05:42'.
Use this
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
setInterval(function(){
var now = new Date();
var time = monthNames[now.getMonth()] + " " + now.getDate() + ", " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
document.getElementById("currentTime").innerHTML = time;
}, 1000);
document.getElementById("name").innerHTML = Intl.DateTimeFormat().resolvedOptions().timeZone + ", ";
<p id="time"><span id="name"></span> <span id="currentTime"></span></p>
// get a new date (locale machine date time)
var date = new Date();
// First converting to UTC and then adding +360 to make it +5 GMT
const millisecondsOffset = ((date.getTimezoneOffset() + 360 ) * 60 * 1000);
date.setTime(date.getTime() - millisecondsOffset);
// get the date as a string
var n = date.toDateString();
// get the time as a string
var time = date.toLocaleTimeString();
// find the html element with the id of time
// set the innerHTML of that element to the date a space the time
document.getElementById('time').innerHTML = 'Islamabad, Karachi'+ ' ' + n + ' ' + time;
<div id='time'></div>

Javascript Countdown Date

probably an easy question for many of you. :)
I'm trying to use the simple counter from this countdown: https://github.com/rendro/countdown and i'm stuck passing javascript variable.
Normally the end date format for this counter is:
var endDate = "June 7, 2087 15:03:25";
then in the function you pass the variable:
$('.countdown.simple').countdown({ date: endDate });
but i'm trying to get a dynamic 24h date and time and sending the output in the same original endDate format. The goal is to have a countdown purchased timer to purchase this product before the end of the day so (time now - and of the day). Unfortunately its not working.
<script type="text/javascript">
var dateNow = new Date();
var monthsArray = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
var monthNow = monthsArray[dateNow.getMonth()];
var dayNow = dateNow.getDate();
var yearNow = dateNow.getFullYear();
var hourNow = dateNow.getHours();
var minNow = dateNow.getMinutes();
var secNow = dateNow.getSeconds();
var completeDate = monthNow + " " + dayNow + ", " + yearNow + " " + hourNow + ":" + minNow + ":" + secNow;
$(function() {
$('.countdown.simple').countdown({ date: completeDate });
});
alert(completeDate);
</script>
i have set an alert to test the output format and its working well. But my counter is showing 0 years, 0 days, 00 hours, 00 min and 00 sec.
whats wrong..
You are setting the end date for the countdown timer to the present date. You need to pass in a future date.
Instead of creating a date string, you can also just pass in a date object.
Example
// Create the date object
var completeDate = new Date();
// Set the date to the last possible second of the day
completeDate.setHours(23, 59, 59);
// Start the timer
$(function() {
$('.countdown.simple').countdown({ date: completeDate });
});

Parse and return components of a date using Javascript

I have a series of dates formatted similar to 2014-12-31 (year, month, day) loading into a webpage.
I'd like to use Javascript to reformat the date to appear as December 31, 2014 (month, day, year).
Is it possible to do this without splitting the string and reformatting; in other words, is it possible to only use Javascripts date() function?
For example, if I try:
d = new Date.parse('2014-12-31')
Is there a way to return only the year, month or day?
I tried d.getYear(), but that threw a "function not found" error.
Can you use momentjs.com? it's far more powerful than the default.
var yourInput = "2014-12-31";
var moment = require("moment");
var d = moment(yourInput);
var iYear = d.year();
var iMonth = d.month();
var iDay = d.day();
It is possible, but what I am showing is not very pretty, so I agree that using the well-established moment.js is a better idea. If you must not use libraries...
You have to be careful if the user is behind GMT, because creating a new Date (without a time in hours) will then be set to the previous day. getTimezoneOffset() is used to correct the desired date to midnight.
Also, you have to define an array of months to be displayed. By default, getting a month returns an integer from 0 to 11. (Jan = 0)
function myDateFormat(ymd) {
var rawDate = new Date(ymd);
var midnight = new Date(rawDate.getTime() +
rawDate.getTimezoneOffset() * 60 * 1000);
var months = ["January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"]
return months[midnight.getMonth()] + " " +
midnight.getDate() + ", " + midnight.getFullYear();
}
// test function
function display(x) {
document.getElementById("result").innerHTML += x + "\n";
}
display("2015-02-15 is " + myDateFormat("2015-02-15"));
display("2014-12-31 is " + myDateFormat("2014-12-31"));
display("2015-10-10 is " + myDateFormat("2015-10-10"));
<pre id="result"></pre>
You should just use var d = new Date('2014-12-31');
Date.parse returns the number of milliseconds since the Unix epoch, not a Date object.

Javascript: Date Issue

I create a new Date in javascript and provide it the string value of a date like so:
>>> string_date = '2009-09-09';
>>> var myDate = new Date(string_date);
>>> myDate
Tue Sep 08 2009 20:00:00 GMT-0400 (EST) { locale="en"}
The string date comes from a calendar picker widget and I write the value from that widget to a hidden input field. The format of the date is YYYY-MM-DD. Also, with the code above, I write the date selected to a div to show the date in a nice way. However, the users are confused by the date shown that way. So, how can I show the date in such a way that the locale is not considered and so, write it as Sep 09, 2009?
Thanks! :)
Something like this?
<script type="text/javascript">
<!--
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(m_names[curr_month] + " " + curr_date + ", " + curr_year);
//-->
</script>
More here: http://www.webdevelopersnotes.com/tips/html/javascript_date_and_time.php3
myDate.toDateString()
If you don't want the day, (1 + myDate.getMonth()) + ' ' + myDate.getDate() + ', ' + myDate.getFullYear().
If you don't need that comma, you can write that as [1 + myDate.getMonth(), myDate.getDate(), myDate.getFullYear()].join(' ')
Edit: Forgot that getMonth() doesn't return human-readable names, and that you'd have to store them in an array as per #NinjaCat.
var parts = myDate.split(' ');
var strDate = parts[1] + ' ' + parts[2] + ', ' + part[3]
If you go the "correct" way and use getXXX remember that getMonth() needs +1 since JS months start at 0.

Categories

Resources