I would like to list all dates and hour of a year with format mmddhh
Q1: Why I got "undefined" before the output? How can I fix it?
var m, d, h, month, day, hour, output;
for (m = 1; m <= 12; m++) {
month = addZero(m).toString();
for (d = 1; d <= 31; d++) {
day = addZero(d).toString();
for (h = 1; h <= 24; h++) {
hour = addZero(h).toString();
output += month + day + hour + "<br>";
}
}
}
document.getElementById("result").innerHTML = output;
function addZero(z) {
var z
if (z < 10)
return "0" + z;
else
return z;
}
<p id="result"></p>
Q2: I tried looping d 31 times using if (m = "01" || "03" || "05" || "07" || "08" || "10" || "12") else looping 30 times. However it is fail, how can I do that?
var m, d, h, month, day, hour, output;
for (m = 1; m <= 12; m++) {
month = addZero(m).toString();
if (m = "01" || "03" || "05" || "07" || "08" || "10" || "12") {
for (d = 1; d <= 31; d++) {
day = addZero(d).toString();
for (h = 1; h <= 24; h++) {
hour = addZero(h).toString();
output += month + day + hour + "<br>";
}
}
} else {
for (d = 1; d <= 30; d++) {
day = addZero(d).toString();
for (h = 1; h <= 24; h++) {
hour = addZero(h).toString();
output += month + day + hour + "<br>";
}
}
}
}
document.getElementById("result").innerHTML = output;
function addZero(z) {
var z
if (z < 10)
return "0" + z;
else
return z;
}
<p id="result"></p>
You have declared a variable called output, but it is not initialized with a value, so its value is undefined.
Then when you say output += month + day + hour + "<br>"; it is really output = undefined + month + day + hour + "<br>";, thus you are getting an undefined at the beginning of the output
var m, d, h, month, day, hour, output = "";
for (m = 1; m <= 12; m++) {
month = addZero(m).toString();
for (d = 1; d <= 31; d++) {
day = addZero(d).toString();
for (h = 1; h <= 24; h++) {
hour = addZero(h).toString();
output += month + day + hour + "<br>";
}
}
}
document.getElementById("result").innerHTML = output;
function addZero(z) {
var z
if (z < 10)
return "0" + z;
else
return z;
}
<p id="result"></p>
Related
It is 4:11PM here now but my output is shown as 'Good Morning' - why is this happening?
$(document).ready(function() {
function dateTime() {
var ndate = new Date();
var h = ndate.getHours() % 12;
var format = h >= 12 ? 'PM' : 'AM';
var m = ndate.getMinutes().toString();
var s = ndate.getSeconds().toString();
if (h < 12) {
h = "0" + h;
$("h3.day-message").html("Good Morning");
} else if (h < 18) {
$("h3.day-message").html("Good Afternoon");
} else {
$("h3.day-message").html("Good Evening");
}
if (s < 10) {
s = "0" + s;
}
if (m < 10) {
m = "0" + m;
}
$('.date').html(h + ":" + m + ":" + s + format);
}
setInterval(dateTime, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>
The issue is because you are using the modulo operator. This means that your h > 12 check will never be hit as the remainder of the division cannot be greater than 12. It's because of this your logic always believes it's still the morning. To fix this, just use a simple < check when comparing the hour figure.
Also note that you have some issues with the formatting of the date, such as appending extra zeroes so you end up with 011 as hour values. You can fix this by using slice().
With all that said, try this:
$(document).ready(function() {
function dateTime() {
var ndate = new Date();
var hours = ndate.getHours();
var message = hours < 12 ? 'Good Morning' : hours < 18 ? 'Good Afternoon' : 'Good Evening';
$("h3.day-message").text(message);
$('.date').html(hours.leadingZeroes(2) + ":" + ndate.getMinutes().leadingZeroes(2) + ":" + ndate.getSeconds().leadingZeroes(2) + (hours < 12 ? 'AM' : 'PM'));
}
setInterval(dateTime, 1000);
});
Number.prototype.leadingZeroes = function(len) {
return (new Array(len).fill('0', 0).join('') + this).slice(-Math.abs(len));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>
$(document).ready(function() {
function dateTime() {
var format="";
var ndate = new Date();
var hr = ndate.getHours();
var h = hr % 12;
if (hr < 12)
{
greet = 'Good Morning';
format='AM';
}
else if (hr >= 12 && hr <= 17)
{
greet = 'Good Afternoon';
format='PM';
}
else if (hr >= 17 && hr <= 24)
greet = 'Good Evening';
var m = ndate.getMinutes().toString();
var s = ndate.getSeconds().toString();
if (h < 12) {
h = "0" + h;
$("h3.day-message").html(greet);
} else if (h < 18) {
$("h3.day-message").html(greet);
} else {
$("h3.day-message").html(greet);
}
if (s < 10) {
s = "0" + s;
}
if (m < 10) {
m = "0" + m;
}
$('.date').html(h + ":" + m + ":" + s + format);
}
setInterval(dateTime, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>
You are calculating mode, so h will never be greater that 12
So, Instead of
var h = ndate.getHours() % 12;
Use it
var h = ndate.getHours();
Explaination: modulo operator(%) will divide total hours by 12 and return the Remainder.
For example if current time is 4 pm, I'll be 16 hours, so It'll return 4
Without jQuery
const messages = [
{ ampm: "am", "greet": 'Good Morning' },
{ ampm: "pm", "greet": 'Good Afternoon' },
{ ampm: "pm", "greet": 'Good Evening' }
];
window.addEventListener("DOMContentLoaded", () => {
const dateSpan = document.getElementById("date");
const message = document.getElementById("day-message");
const dateTime = () => {
let now = new Date(),
hour = now.getHours(),
hh = hour % 12, // (hour % 12).toString().padStart(2,"0") if you want leading 0
mm = now.getMinutes().toString().padStart(2,"0"),
ss = now.getSeconds(),
period = 0;
if (hour < 12) period = 0;
else if (hour >= 12 && hour < 17) period = 1;
else if (hour >= 17 && hour <= 24) period = 2;
message.textContent = messages[period].greet;
dateSpan.textContent = `${hh}:${mm}${messages[period].ampm}`;
};
setInterval(dateTime, 500);
});
<h3 id="day-message"></h3>
<span id="date"></span>
Display Good Morning/Afternoon/Evening using javascript in 12hours format
const displayGreeting =()=>{
const myDate = new Date();
const hrs = myDate.getHours();
let greet;
if (hrs < 12)
greet = 'Good Morning';
else if (hrs >= 12 && hrs <= 17)
greet = 'Good Afternoon';
else if (hrs >= 17 && hrs <= 24)
greet = 'Good Evening';
return greet
}
I'm trying to create a range of dates that can be parsed by daily or weekly granularity and have hit a roadblock. I have a function that allows you to enter a start month,start year, end month, end year, and granularity and returns the date range according to the granularity.
I am able to run this successfully for daily granularity, but when running for weekly granularity, every new month restarts at 1. Looking at the below example:
2015-11-01 2015-11-08 2015-11-15 2015-11-22 2015-11-29 2015-12-01 2015-12-08 2015-12-15 2015-12-22 2015-12-29 2016-01-01 2016-01-08
I would like it to appear as:
2015-11-01 2015-11-08 2015-11-15 2015-11-22 2015-11-29 2015-12-06 2015-12-13 2015-12-20 2015-12-27 2016-01-03
I understand why this is happening - at the end of each for loop the variable "d" is force set to 1. I tried to add additional if statements after the "dates.push(y+"-"+m+"-"+d)" but I know that is really inefficient coding. I added the snippit of what I tried below:
if monthday(m,y) – d < 7 {
d = monthday(m,y) –d
if m = 12 {
m = 1
y = y+1
else {
m = m+1
}
}
The functions used are copied below.
Any insight into how I could do this would be much appreciated!
/// Function to decide how many days in a month
function monthday (month,year) {
var months31 = [1,3,5,7,8,10,12]
var months30 = [4,6,9,11]
var leapyear = [2016,2020,2024,2028,2032] /// if this code is still being used in 2036 I'll eat my hat
if (months31.indexOf(month) >=0){
var result = 31}
else if (months30.indexOf(month) >=0){
var result = 30}
else if (month==2 && leapyear.indexOf(year) >=0){
var result = 29}
else if (month==2 && year != 2016){
var result = 28}
return result
}
////Date Range - calculates # of days/weeks between 2 date ranges
function dateRange (start_month,start_year,end_month,end_year,granularity) {
var dates = [];
var d0 = [start_year,start_month];
var d1 = [end_year,end_month];
switch (granularity) {
case "Daily":
for (var y = d0[0]; y <= d1[0]; y++) {
if ((y == d0[0]) && (d0[0] != d1[0])) { // if year=start_year && year != end year ... start from start_month and loop up to month 12
for (var m = d0[1]; m <= 12; m++) {
for (var d =1;d <= monthday(m,y); d++) {
dates.push(y+"-"+m+"-"+d)
}
}
}
if ((y != d0[0]) && (y!= d1[0])) { // if year != start_year && year != end year .... start from month 1 to month 12 - this would 2015 data in pulling Dec 2014 - April 2016
for (var m = 1; m <= 12; m++) {
for (var d =1;d <= monthday(m,y); d++) {
dates.push(y+"-"+m+"-"+d)
}
}
}
if ((y != d0[0]) && (y == d1[0])) { // if year !=start_year && year = end_year .... start from month 1 up until end_month
for (var m = 1; m <= d1[1]; m++) {
for (var d =1;d <= monthday(m,y); d++) {
dates.push(y+"-"+m+"-"+d)
}
}
}
if ((y == d0[0]) && (y == d1[0])) { /// if year=start_year && year = end_year .... start from start_month to end_month
for (var m = d0[1]; m <= d1[1]; m++) {
for (var d =1;d <= monthday(m,y); d++) {
dates.push(y+"-"+m+"-"+d)
}
}
}
}
break;
case "Weekly":
for (var y = d0[0]; y <= d1[0]; y++) {
if ((y == d0[0]) && (d0[0] != d1[0])) { // if year=start_year && year != end year ... start from start_month and loop up to month 12
for (var m = d0[1]; m <= 12; m++) {
for (var d =1;d <= monthday(m,y); d+=7) {
dates.push(y+"-"+m+"-"+d)
}
}
}
if ((y != d0[0]) && (y!= d1[0])) { // if year != start_year && year != end year .... start from month 1 to month 12 - this would 2015 data in pulling Dec 2014 - April 2016
for (var m = 1; m <= 12; m++) {
for (var d =1;d <= monthday(m,y); d+=7) {
dates.push(y+"-"+m+"-"+d)
}
}
}
if ((y != d0[0]) && (y == d1[0])) { // if year !=start_year && year = end_year .... start from month 1 up until end_month
for (var m = 1; m <= d1[1]; m++) {
for (var d =1;d <= monthday(m,y); d+=7) {
dates.push(y+"-"+m+"-"+d)
}
}
}
if ((y == d0[0]) && (y == d1[0])) { /// if year=start_year && year = end_year .... start from start_month to end_month
for (var m = d0[1]; m <= d1[1]; m++) {
for (var d =1;d <= monthday(m,y); d+=7) {
dates.push(y+"-"+m+"-"+d)
}
}
}
}
break;
}
return dates
}
You don't need to control the month length, let Date object do it for you.
function formatDate(date) {
return date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).substr(-2) + '-' + ('0' + date.getDate()).substr(-2);
}
function dateRange (start_month,start_year,end_month,end_year,granularity) {
var date = new Date(start_year + '-' + start_month + '-01');
var endDate = new Date(end_year + '-' + end_month + '-01');
var arr = [];
while(date < endDate) {
arr.push(formatDate(date));
switch (granularity) {
case 'Daily':
date.setDate(date.getDate() + 1); // date++
break;
case 'Weekly':
date.setDate(date.getDate() + 7); // week++
break;
case 'Monthly':
date.setMonth(date.getMonth() + 1);
break;
// ...
}
}
return arr;
}
Is it something you were looking for?
I'd like to get a current timestamp object which is minutes l。 How do I do it with JavaScript?
Here my code :
var mins = "";
var new_timestamp = parseInt($("#current_time").data("timestamp")) + 1000;
var date = new Date(new_timestamp);
for (var b = 0; b < 60; b++) {
if (b == date.getMinutes()) {
str += "<option selected>" + (b < 10 ? ("0" + b) : b) + "</option>";
} else {
str += "<option>" + (b < 10 ? ("0" + b) : b) + "</option>";
}
}
$("#bank-order-time [name=\"minutes\"]").html(mins);
HTML :
<select name="minutes">
var date = new Date();
new Date() gives you a Date object of then time. You don't need to input a timestamp.
And date.getMinutes() give you the minute as you already know.
And if you need to get the current time again, remember you need to create a new Date object and do not use the old one.
My answer:
(function(){
var str ="";
var new_timestamp = parseInt($("#current_time").data("timestamp"))+1000;
var date = new Date(new_timestamp);
for( var a = 0; a < 24 ; a++)
{
if( a== date.getHours() )
{
str +="<option selected>"+(a<10?("0"+a):a)+"</option>" ;
}
else
{
str +="<option>"+(a<10?("0"+a):a)+"</option>" ;
}
}
$("#bank-order-time [name=\"hour\"]").html(str);
var mins = "";
for( var b = 0; b < 60; b++)
{
if( b == date.getMinutes())
{
mins +="<option selected>"+(b<10?("0"+b):b)+"</option>" ;
}
else
{
mins +="<option>"+(b<10?("0"+b):b)+"</option>" ;
}
}
$("#bank-order-time [name=\"minutes\"]").html(mins);
})();
This is a script that counts a desired number of business days from the present time. It works very well. I would like it to render the result as a long word day of the week, as in Monday July 06 2015, for example. The current result is Mon Jul 06 2015
I am a hacking monkey, so a dumbed-down response would not be an insult!
Number.prototype.mod = function(n) {
return ((this % n) + n) % n;
}
Date.prototype.addBusDays = function(dd) {
var wks = Math.floor(dd / 5);
var dys = dd.mod(5);
var dy = this.getDay();
if (dy === 6 && dd > -1) {
if (dys === 0) {
dys -= 2;
dy += 2;
}
dys++;
dy -= 6;
}
if (dy === 0 && dd < 1) {
if (dys === 0) {
dys += 2;
dy -= 2;
}
dys--;
dy += 6;
}
if (dy + dys > 5) dys += 2;
if (dy + dys < 1) dys -= 2;
this.setDate(this.getDate() + wks * 7 + dys);
}
var today = new Date();
today.addBusDays(1);
document.getElementById('dtt').innerHTML = today.toDateString();
Usage: We use it in a full sentence:
Your package will arrive on or before <span id="dtt"></span>.
Just create an array of month/day names like so:
var days = ["Sunday","Monday",...];
var months = ["January", "February", ...];
And then
function formatDate(date) {
var day = date.getDate();
if(day < 10) {
day = "0" + day;
}
return days[date.getDay()] + " " + months[date.getMonth()] + " " + day + " " + date.getFullYear();
}
console.log(formatDate(new Date()));
http://jsfiddle.net/1xe39uut/2/
I have a Javascript countdown from 12am to 9pm each day and then resets itself.
I want the countdown to go from 8am-9pm instead of 12am-9pm. I have been fiddling with this but I can't seem to make it work with a start time other than the defaulted 12am.
My question is how can I make the countdown from 8-21 hours instead of 0-21 hours?
Javascript:
if (document.getElementById('countdown')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown(){
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 7) ) { // Monday to Sunday
var target = 21; // 21:00hrs is the cut-off point
if (now.getHours() < target) { //
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdown').innerHTML = str;
}
else
$('.wereOpen').hide();
}
}
var timerRunning = setInterval('countDown()', 1000);
}
Website
I don't fully understand your question, but could you just add now.getHours() >= 7 to your if statement, i.e.
...
if (now.getHours() >= 7 && now.getHours() < target) {
...
} else {
$('.wereOpen').hide();
}
...
EDIT
In light of the comment, the following should work:
if (document.getElementById('countdown')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown(){
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 7) ) { // Monday to Sunday
var target = 21; // 21:00hrs is the cut-off point
var hours = now.getHours(); //get hours
if(hours < 8 || hours >= target) {
$('.wereOpen').hide();
return;
} else
$('.wereOpen').show();
var hrs = (target - 1) - hours;
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdown').innerHTML = str;
}
}
var timerRunning = setInterval('countDown()', 1000);
}