I'm using javascript to display the current (live) date/time on a website. I want all the numbers (date, hour, minute, second) to always display with 2 digits. So if a number is (0-9) it is prefixed with a '0'
I've managed to do this for the time counter. But I can't seem to work the same code into getDate without breaking the script.
If someone could help with that it'd be greatly appreciated and also confirm if my approach isn't massively overcomplicated!
function showDateTime() {
var currentDate = document.getElementById("date");
var currentTime = document.getElementById("time");
var date = new Date();
var dayList = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var monthNames = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
var dayName = dayList[date.getDay()];
var monthName = monthNames[date.getMonth()];
var today = `${dayName} ${date.getDate()} ${monthName}`;
var hour = ('0'+date.getHours()).substr(-2);
var min = ('0'+date.getMinutes()).substr(-2);
var sec = ('0'+date.getSeconds()).substr(-2);
var time = hour + ":" + min + ":" + sec;
currentDate.innerText = `${today}`;
currentTime.innerText = `${time}`;
}
setInterval(showDateTime, 1000);
<div id="date"></div>
<div id="time"></div>
const date = new Date();
const now = date.toLocaleTimeString(); // "11:33:01"
You could also use const instead of var because the value will never change.
function showDateTime() {
const currentDate = document.getElementById("date");
const currentTime = document.getElementById("time");
const date = new Date();
const dayList = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const monthNames = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
const dayName = dayList[date.getDay()];
const monthName = monthNames[date.getMonth()];
const today = `${dayName} ${date.getDate()} ${monthName}`;
const time = date.toLocaleTimeString();
currentDate.innerText = `${today}`;
currentTime.innerText = `${time}`;
}
setInterval(showDateTime, 1000);
Related
How to turn a period of date in an array? For example, I have a period of date from 1 March 2020 to 29 April 2020, how can I turn it into an array shown below?
period = [{day: "Sun", date: "1", month: "Mar", year: "2020"}, ...,
{day: "Wed",date: "29", month: "Apr", year: "2020"}]
You can create array from date range follow https://stackoverflow.com/a/50398144/4964569
and get day in date follow https://stackoverflow.com/a/4822882/4964569
And use map function to generate your required
var getDaysArray = function(s,e) {for(var a=[],d=new Date(s);d<=e;d.setDate(d.getDate()+1)){ a.push(new Date(d));}return a;};
var dateRange = getDaysArray(new Date('2020-03-10'), new Date('2020-04-29'));
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var result = dateRange.map(function(elem){
var obj = {
day: days[elem.getDay()],
date: elem.getDate(),
month: elem.getMonth(),
year: elem.getFullYear()
}
return obj;
});
console.log(result)
var getDaysArray = function(s,e) {for(var a=[],d=new Date(s);d<=e;d.setDate(d.getDate()+1)){ a.push(new Date(d));}return a;};
var dateRange = getDaysArray(new Date('2020-03-10'), new Date('2020-04-29'));
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var result = dateRange.map(function(elem){
var obj = {
day: days[elem.getDay()],
date: elem.getDate(),
month: elem.getMonth(),
year: elem.getFullYear()
}
return obj;
});
console.log(result)
In traditional way you can do it like this
var startDate = new Date('2020-03-10');
var endDateDate = new Date('2020-03-12');
var arr = [];
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
while(startDate.getTime() !== endDateDate.getTime()) {
startDate.setDate(startDate.getDate() + 1)
arr.push({
day: days[startDate.getDay()],
date: startDate.getDate(),
month: startDate.getMonth(),
year: startDate.getYear()
})
}
console.log(arr);
I'm assuming you have two Dates as your range delimiters. If not, you can create them this way:
var startDate = new Date('1 March 2020')
var endDate = new Date('29 April 2020')
Then, you have to increase the first date by one day until you reach the last date. To increase the first date by one day you can do this:
startDate.setDate(startDate.getDate() + 1)
You can get the day and the month from a Date with date.getDay() and date.getMonth(), but those methods will return numbers. To get the actual names you can do this:
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
var startDateDay = days[startDate.getDay()]
var startDateMonth = months[startDate.getMonth()]
And then, you iterate:
var period = []
while (startDate <= lastDate) {
period.push({
day: days[startDate.getDay()],
date: startDate.getDate(),
month: months[startDate.getMonth()],
year: startDate.getYear()
})
startDate.setDate(startDate.getDate() + 1)
}
And that's it. Here's a fiddle with a working example:
var startDate = new Date('1 March 2020')
var endDate = new Date('29 April 2020')
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
var period = []
while (startDate <= endDate) {
period.push({
day: days[startDate.getDay()],
date: startDate.getDate(),
month: months[startDate.getMonth()],
year: startDate.getFullYear()
})
startDate.setDate(startDate.getDate() + 1)
}
console.log(period)
var start = new Date('March 1, 2020');
var period = [];
for(var i=1; i<=60; i++){
if( i == 32 )
start = new Date('April 1, 2020');
if( i <= 31 )
start.setDate(i);
else
start.setDate(i - 31);
var dateString = start.toDateString().split(' ');
period.push({
day: dateString[0],
date: dateString[2],
month: dateString[1],
year: dateString[3]
});
}
console.log( JSON.stringify(period) );
I am trying to write an apps script and assign it to a button. When the button is pressed, it will activate a function I named clockin(). What this function does is to look for today's date on column B and write the current time on column C. The problem is this code is not writing any value on the defined cell which kinda sucks. I'm new to Javascript, hence requiring your assistance. My code is below:
function todayDateNowTime () {
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var today = new Date()
var month = monthNames[today.getMonth()]; //months from 1-12
var day = today.getDate();
var year = today.getFullYear();
var seconds = today.getSeconds();
var minutes = today.getMinutes();
var hour = today.getHours();
var todayDate = day+"-"+month+"-"+year;
var nowTime = hour+":"+minutes+":"+seconds;
console.log(todayDate);
console.log(nowTime);
return todayDate, nowTime;
}
function clockin(todayDate, nowTime) {
todayDate, nowTime = todayDateNowTime();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = sheet.getDataRange().getValues();
for(var i = 0; i<data.length;i++){
if(data[i][1] == todayDate) { //[1] because column B
var range = SpreadsheetApp.getActiveSpreadsheet().getActiveCell("C"+i)
range.setValue(nowTime);
}
}
}
I have made my gsheet publically available to view right here.
I have also included a screenshot here if it helps:
I made some small adjustments to your code. See if it now works?
function todayDateNowTime () {
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec"];
var today = new Date()
var month = monthNames[today.getMonth()]; //months from 1-12
var day = today.getDate();
day = day < 10 ? "0" + day : day;
var year = today.getFullYear();
var seconds = today.getSeconds();
var minutes = today.getMinutes();
var hour = today.getHours();
var todayDate = day+"-"+month+"-"+year;
var nowTime = hour+":"+minutes+":"+seconds;
return [todayDate, nowTime];
}
function clockin() {
var dateAndTime = todayDateNowTime();
var todayDate = dateAndTime[0];
var nowTime = dateAndTime[1];
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = sheet.getDataRange().getDisplayValues();
for(var i = 0; i<data.length;i++){
if(data[i][1] == todayDate) { //[1] because column B
var range = sheet.getRange(i+1, 3)
range.setValue(nowTime);
}
}
}
My function displays the current date along with the next 60 days however I want the current date to be highlighted. What would be the best approach?
var date = new Date();
var dayInt = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var dateRange = document.getElementById('calendar-table-range');
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
document.getElementById("month").innerHTML = monthNames[month];
document.getElementById("year").innerHTML = year;
for(var day = 0; day < 60; day++) {
var date = new Date();
date.setDate(date.getDate() + day);
var cell = document.createElement("li");
var cellText = document.createTextNode(day);
var date = ('0' + date.getDate()).slice(-2) + ' '
+ monthNames[date.getMonth()] + ' '
// + date.getFullYear();
cell.innerHTML = date;
dateRange.appendChild(cell);
}
Since you're always showing the next 60 days, the current date is always the first date in the list, so it's easy to target with a CSS selector. For example:
#calendar-table-range li:first-child {
background-color: yellow;
}
Another way to go about it is to create a timestamp in the same format as the dates in the range then search for it.
E.g. the following, which puts formatting into a separate function and removes code that wasn't being used:
function formatDate(d){
let monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return ('0 ' + d.getDate()).slice(-2) + ' '
+ monthNames[d.getMonth()];
}
function highlightToday() {
let today = formatDate(new Date());
let cells = document.querySelectorAll('#calendar-table-range > li');
for (var i=0, iLen=cells.length; i<iLen; i++) {
if (cells[i].textContent == today) {
cells[i].style.color = 'red';
return;
}
}
}
var date = new Date();
var dayInt = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var dateRange = document.getElementById('calendar-table-range');
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
document.getElementById("month").innerHTML = monthNames[month];
document.getElementById("year").innerHTML = year;
for(var day = 0; day < 6; day++) {
var date = new Date();
date.setDate(date.getDate() + day);
var cell = document.createElement("li");
var date = formatDate(date);
cell.innerHTML = date;
dateRange.appendChild(cell);
}
<div id="month"></div>
<div id="year"></div>
<input type="button" onclick="highlightToday()" value="highlight today">
<ol id="calendar-table-range">
</ol>
How to format the javascript Date object the way stackoverflow does it.
For example. Aug 23 '10 at 23:35
This is what I tried.
new Date(val.replace(' ','T')+'Z').toString().split('GMT')[0]
This works cross browser. But doesn't look neat.
function formatDate(date) {
var monthNames = [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct",
"Nov", "Dec"
];
var day = date.getDate();
var monthIndex = date.getMonth();
var month = monthNames[monthIndex];
var year = date.getFullYear().toString().substring(2,3);
var hours = date.getHours();
var minutes = date.getMinutes();
return month+' '+day+" '"+year+' at '+hours+':'+minutes;
}
Try this:
var date = new Date();
var formattedDate =
(date.toLocaleString("en-us", { month: "long" })) + " " +
date.getDate() + " '" + (date.getFullYear() % 100);
var formattedTime = date.getHours() + ':' + date.getMinutes();
alert( formattedDate + " at " + formattedTime );
Here's a JSFiddle.
I'm trying to change the date format for some data coming in. I can change it to this format "02-10" but i wanted it to look like this "Feb 10 2015"
So far i have something like this that changes it to each day of the week, but i would like to change that. Here's what i have.
$scope.hourlyData = [];
var hourData = [];
var hourItem = [];
var dailyData = [];
var day;
var date;
var Everymonth = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var item = ['Day', 'Number of Interactions', {role: 'style'}];
dailyData.push(item);
var dailyReports = $scope.tweetReports.dailyReports;
$scope.numberOfdailyReports = dailyReports.length;
for (var i = 0; i < dailyReports.length; i++) {
if (dailyReports[i] != null) {
//console.log("Tweets on " + dailyReports[i].day + ":" + dailyReports[i].tweets);
day = dailyReports[i].day.split(" ")[0];
date = dailyReports[i].day.split(" ")[1];
date = date.substr(date.indexOf('-') + 1);
if (numDays =< 7) {
day = day.toLowerCase();
day = day.charAt(0).toUpperCase() + day.substr(1);
} else {
day = date;
}
If you are open to use libraries, You can use momentJS like this
jsfiddle
var dateString = "2013-07-18";
var date = moment(dateString).format('MMM DD YYYY');