I might be making things overly complicated :p
But I can't get it to work.
I'm trying to copy "todays date"
to the clipboard
Date
<script>
function copydateToClipboard() {
Date.prototype.toShortFormat = function() {
const monthNames = ["January", "February", "March", "April",
"May", "Juni", "July", "August",
"September", "October", "November", "December"];
const day = this.getDate()-1;
const monthIndex = this.getMonth();
const monthName = monthNames[monthIndex];
const year = this.getFullYear();
return `${year}_${monthName}_${day}`; }
let anyDate = new Date(1528578000000);
console.log(anyDate.toShortFormat());
let today = new Date();
//copydate to clipboard
const str = "${today}"
const el = document.createElement('textarea')
el.value = str
el.setAttribute('readonly', '')
el.style.position = 'absolute'
el.style.left = '-9999px'
document.body.appendChild(el)
el.select()
document.execCommand('copy')
document.body.removeChild(el)
}
</script>
Taken from an url reform script.
Got it:
Date
<script>
function copydateToClipboard() {
var nowd = new Date().toUTCString().slice(0,16);
//const str = "${nowd}"
const el = document.createElement('textarea')
el.value = nowd
el.setAttribute('readonly', '')
el.style.position = 'absolute'
el.style.left = '-9999px'
document.body.appendChild(el)
el.select()
document.execCommand('copy')
document.body.removeChild(el)
}
</script>
Related
I am trying to create a calendar using Nodejs, EJS and Mongodb wherein one can write events for a particular day. The events get stored in a collection called Names in a mongodb database called Sample Database.
This is the code in app.js file.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const { MongoClient } = require("mongodb");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
const uri =
"mongodb+srv://netTheCoder:welcome#cluster0.ra2eh5p.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri);
var eventItems = [];
var eventsObj={};
var events_arr = [];
var inputEvent,inputDate;
var added;
app.get("/calendar",function(req,res){
console.log(events_arr);
res.render('calendar',{newListItem: eventItems, added : added, eventsArr : events_arr}); })
app.post("/calendar",function(req,res){
inputEvent = req.body.eventInput inputDate = req.body.eventDate;
eventsObj= {
date:inputDate,
description: inputEvent
}
events_arr.push(eventsObj)
console.log(eventsObj);
// obj={
// user :"user1",
// events: events_arr // }
AddEvents().catch(console.dir);
eventItems.push(inputEvent);
added = true;
res.redirect("/calendar");
})
async function AddEvents() {
try {
const database = client.db('SampleDatabase');
const names = database.collection('n');
//Adding events to calendar
const addedItem = await names.insertOne(eventsObj);
console.log("Item added successfully")
console.log(addedItem);
// Query for a movie that has the title 'Back to the Future'
} finally {
} }
async function getEvents() {
try {
const database = client.db('SampleDatabase');
const names = database.collection('Names');
//Adding events to calendar
const addedItem = await names.find();
console.log("Item added successfully")
console.log(addedItem);
// const query = { date: "16-12-22"};
// const event = await names.find(query); }
finally { //
// Ensures that the client will close when you finish/error // await client.close(); } }
server.listen(3000,function(req,res){ console.log("The server is running at port 3000"); })
The calendar.js file
const currentDate = $(".current-date"),
daysTag = $(".days"),
prevNextIcons = document.querySelectorAll(".calender-icons span");
//getting the present date, year and month
let date = new Date(),
currentYear = date.getFullYear(),
currentMonth = date.getMonth();
console.log(currentMonth)
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const renderCalendar = () => {
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let firstDayofMonth = new Date(currentYear, currentMonth, 1).getDay();
let lastDateofMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
let lastDayofMonth = new Date(currentYear, currentMonth, lastDateofMonth ).getDay()
let lastDateofLastMonth = new Date(currentYear, currentMonth, 0).getDate();
let liTag = "";
for (let i = firstDayofMonth ; i > 0; i--) {
liTag += `<li class="day inactive">${lastDateofLastMonth-i +1}</li>`
}
for (let i = 1; i <= lastDateofMonth; i++) {
let isToday = i === date.getDate() && currentMonth === new Date().getMonth()
&& currentYear === new Date().getFullYear() ? "active" :"";
liTag += `<li class="day ${isToday}">${i}</li>`
}
for(let i =lastDayofMonth; i<6 ;i++){
liTag += `<li class="day inactive">${i-lastDayofMonth +1}</li>`
}
currentDate.text(`${months[currentMonth]} ${currentYear}`);
daysTag.html(liTag)
}
renderCalendar();
prevNextIcons.forEach(icon => {
icon.addEventListener("click", () => {
if (icon.id === "prev") {
if (currentMonth === 0) {
currentMonth = 11;
currentYear = currentYear - 1;
} else {
currentMonth = currentMonth - 1;
}
console.log(currentMonth);
renderCalendar();
dateClicked();
} else {
if (currentMonth === 11) {
currentMonth = 0;
currentYear = currentYear + 1;
} else {
currentMonth = currentMonth + 1;
}
console.log(currentMonth);
renderCalendar();
dateClicked();
}
})
})
let dateObj = new Date();
let today = String(dateObj.getDate()).padStart(2, '0');
$(".event-date").text(today +" " + months[currentMonth]);
let eventLi ="";
var eventAddedDay;
dateClicked();
function dateClicked(){
selectedDate = document.querySelectorAll(".day")
selectedDate.forEach(day=>{
day.addEventListener("click",()=>{
var clickedDate = day.textContent;
$(".event-date").text(clickedDate + " " + months[currentMonth]);
let clickedMonth = currentMonth+1;
let output = currentYear + '-' + clickedMonth + '-' + clickedDate;
console.log("clicked");
$(".events-date").attr('value' ,output );
})
})
}
The code for calendar in calendar.ejs file. This file is linked to calendar.js file.
<div class="calendar">
<ul class="weeks">
<li>Sun</li>
<li>Mon</li>
<li>Tues</li>
<li>Wed</li>
<li>Thurs</li>
<li>Fri</li>
<li>Sat</li>
</ul>
<ul class="days"></ul>
</div>
</div>
</div>
<div id = "events">
<h3 class="event-date"></h3>
<ul type="disc" class="events">
<% for(let i = 0; i<newListItem.length; i++){ %>
<li> <%= newListItem[i] %></li>
<% } %>
</ul>
<p class="retured-date" hidden>
</p>
<form method="post" action="/calendar">
<input class="events-date" type="date" name="eventDate" placeholder="Date">
<input class="event-input" type="text" name="eventInput" placeholder="Your event">
<button type="submit" class="btn btn-outline-dark">Add</button>
</form>
</div>
I was trying to send this data through ejs to my HTML calendar page. So when I click on a day in the calendar the events stored in the database for that particular day should be displayed in the events section . I don't know why but I have tried all possible ways to tackle this but none of them seem to work.
Good day,
This is some sort of a journal I'm trying to make, the localStorage setItem part is fine, it's the getItem I'm having trouble with, after adding the entries to the table, when I refresh, all of the entries are gone and I'm only left with 1 row with the default input values, ("state?" and "").
JS code:
const state = document.querySelector("#state");
const why = document.querySelector(".why");
const button = document.querySelector(".button");
const table = document.querySelector(".table");
var currentDate = new Date();
let cDay = currentDate.getDate();
let cMonth = currentDate.getMonth() + 1;
let cYear = currentDate.getFullYear();
let cDate = cMonth + "-" + cDay;
var sArray = [];
// Check if there's data in local storage
if (localStorage.getItem("states")) {
sArray = JSON.parse(localStorage.getItem("states"));
}
getDataFromLocalStorage();
button.addEventListener("click", () => {
if (state.value !== "state?") {
addToArray();
why.value = "";
state.value = "state?";
}
});
function addToArray() {
addToTable();
addDataToLocalStorage();
}
function addDataToLocalStorage() {
window.localStorage.setItem("states", JSON.stringify(sArray));
}
function addToTable() {
// Object
let dataObject = {
state: state.value,
reason: why.value,
};
// Add to array
sArray.push(dataObject);
const tr = document.createElement("tr");
const tdstate = document.createElement("td");
const tdWhy = document.createElement("td");
const tdDate = document.createElement("td");
tr.appendChild(tdstate);
tr.appendChild(tdWhy);
tr.appendChild(tdDate);
table.appendChild(tr);
tdstate.innerText = dataObject.state;
tdWhy.innerText = dataObject.reason;
tdDate.innerText = cDate;
}
function getDataFromLocalStorage() {
let data = window.localStorage.getItem("states");
if (data) {
let states = JSON.parse(data);
addToTable(states);
}
}
And this is the HTML code
<body>
<h1>How are you feeling today?</h1>
<div class="content">
<div class="form">
<select name="state" id="state">
<option>State?</option>
<option value="very happy">Very happy</option>
<option value="happy">Happy</option>
<option value="okay">Okay</option>
<option value="sad">Sad</option>
<option value="terrible">Terrible</option>
</select>
<input class="why" type="text" placeholder="Why?" />
<input class="button" type="button" value="Add" />
</div>
<table class="table">
<th>State</th>
<th>Reason</th>
<th>Date</th>
</table>
</div>
<script src="script.js"></script>
</body>
you call addToTable(states); but this function doesn't accept any parameters function addToTable() {.
and it seams like a problem in your logic.
you write it to sArray but never use this values.
here a blind try, not tested it:
const state = document.querySelector("#state");
const why = document.querySelector(".why");
const button = document.querySelector(".button");
const table = document.querySelector(".table");
// Date
var currentDate = new Date();
let cDay = currentDate.getDate();
let cMonth = currentDate.getMonth() + 1;
let cYear = currentDate.getFullYear();
let cDate = cMonth + "-" + cDay;
var sArray = [];
getDataFromLocalStorage();
button.addEventListener("click", () => {
if (state.value !== "state?") {
addToArray({
state: state.value,
reason: why.value,
});
why.value = "";
state.value = "state?";
}
});
function addToArray(dataObject) {
sArray.push(dataObject);
addToTable(dataObject);
addDataToLocalStorage();
}
function addDataToLocalStorage() {
window.localStorage.setItem("states", JSON.stringify(sArray));
}
function addToTable(dataObject) {
const tr = document.createElement("tr");
const tdstate = document.createElement("td");
const tdWhy = document.createElement("td");
const tdDate = document.createElement("td");
tr.appendChild(tdstate);
tr.appendChild(tdWhy);
tr.appendChild(tdDate);
table.appendChild(tr);
tdstate.innerText = dataObject.state;
tdWhy.innerText = dataObject.reason;
tdDate.innerText = cDate;
}
function getDataFromLocalStorage() {
let data = window.localStorage.getItem("states");
if (data) {
sArray = JSON.parse(data);
for(const row of sArray) {
addToTable(row);
}
}
}
There are multiple issues. I would suggest, you should follow the SOLID principle and divide function according to its work. Same time, Instead of creating variables and syncing with storage could be an issue. So directly modifying the localStorage is a good choice.
const stateBtn = document.querySelector("#state");
const whyBtn = document.querySelector(".why");
const addBtn = document.querySelector(".button");
const table = document.querySelector(".table");
// Date
var currentDate = new Date();
let cDay = currentDate.getDate();
let cMonth = currentDate.getMonth() + 1;
let cYear = currentDate.getFullYear();
let cDate = cMonth + "-" + cDay;
addBtn.addEventListener("click", () => {
if (stateBtn.value !== "state?") {
const row = { reason: whyBtn.value, state: stateBtn.value };
addDataToLocalStorage(row);
addToTable(row);
whyBtn.value = "";
stateBtn.value = "state?";
}
});
function addDataToLocalStorage(row) {
const states = [...getDataFromLocalStorage(), row];
localStorage.setItem("states", JSON.stringify(states));
}
function renderTable() {
const states = getDataFromLocalStorage();
for (let row of states) {
addToTable(row);
}
}
function addToTable(row) {
const tr = document.createElement("tr");
const tdstate = document.createElement("td");
const tdWhy = document.createElement("td");
const tdDate = document.createElement("td");
tr.appendChild(tdstate);
tr.appendChild(tdWhy);
tr.appendChild(tdDate);
table.appendChild(tr);
tdstate.innerText = row.state;
tdWhy.innerText = row.reason;
tdDate.innerText = cDate;
}
function getDataFromLocalStorage() {
let data = localStorage.getItem("states") || "[]";
return JSON.parse(data);
}
renderTable();
Below is my code- I need to restrict the user to select only sundays in the date picker, the rest days should be greyed out.So the date picker should only show sundays.
Please help me on this. Below code is working good, it defaults date to 4 week out from today and user can change it if possible.
<script type="text/javascript">
var j$ = jQuery.noConflict();
var d = new Date();
d.setDate( d.getDate()+28);
var fromDateStart = new Date( d );
var d = new Date();
d.setDate( d.getDate()+29);
var toDateStart = new Date( d );
j$('.fromdatepickerctl').datepicker({
startDate: getTodayDate()
}).on("changeDate", function(e) {
var fromDate = document.getElementById( e.target.id ).value;
console.log('----> fromDate: '+fromDate);
var d = new Date( Date.parse(fromDate) );
d = d.setDate( d.getDate()+28);
j$('.todatepickerctl').datepicker('setDate', new Date(d) );
});
j$('.todatepickerctl').datepicker({
startDate: getTodayDate()
}).on("changeDate", function(e){
var fromDateStr = j$(".fromdatepickerctl").val();
var toDateStr = document.getElementById( e.target.id ).value;
var parsedFromDate = new Date( Date.parse( fromDateStr ) );
var parsedToDate = new Date( Date.parse(toDateStr ) );
if( parsedFromDate > parsedToDate ){
alert('To Date can not be less than From Date.');
document.getElementById( e.target.id ).value = '';
return false;
}
})
j$('.fromdatepickerctl').datepicker('update', fromDateStart );
j$('.todatepickerctl').datepicker('update', toDateStart );
function getTodayDate(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
today = mm + '/' + dd + '/' + yyyy;
//document.write(today);
return today;
}
</script>
I assume this is the same issue that you are facing .
This enables only Sunday in the datepicker .
jquery ui date picker limit to Sundays
$(function(){
$("#thedate").datepicker({
dateFormat: 'dd-mm-yy',
minDate: 1,
beforeShowDay: enableSUNDAYS
});
// Custom function to enable SUNDAY only in jquery calender
function enableSUNDAYS(date) {
var day = date.getDay();
return [(day == 0), ''];
}
});
I'm working on angularjs application.I have two date fields, requirement is when user selects date in Available Date calendar,the Expire Date field should enable and user should be able to choose the date with in 24days from the date selected in Available Date field.
Example, when user selects date in Available Date field as 2017-03-02, the expire Date field should enable and the calendar should only enable 24days followed by 2017-03-02 (i.e.,2017-03-25), and all dates should be disabled so that user cannot able to select any date after 2017-03-25 or before 2017-03-02..
Please find the demo here
js code:
myApp.controller("myController", ["$scope",
function($scope) {
var today = new Date();
$scope.AvailableDate = new Date();
$scope.ExpireDate = new Date();
$scope.dateFormat = 'yyyy-MM-dd';
$scope.availableDateOptions = {
formatYear: 'yy',
startingDay: 1,
minDate: "2016-03-12",
maxDate: today
};
$scope.expireDateOptions = {
formatYear: 'yy',
startingDay: 1,
minDate: today,
maxDate: "2017-06-12"
};
$scope.availableDatePopup = {
opened: false
};
$scope.expireDatePopup = {
opened: false
};
$scope.ChangeExpiryMinDate = function(availableDate) {
if (availableDate != null) {
var expiryMinDate = new Date(availableDate);
$scope.expireDateOptions.minDate = expiryMinDate;
$scope.ExpireDate = expiryMinDate;
//code to set maxDates in Expire Date field -start
var date = new Date(expiryMinDate);
var newdate = new Date(date);
newdate.setDate(newdate.getDate() + 3);
var dd = newdate.getDate();
var mm = newdate.getMonth() + 1;
var y = newdate.getFullYear();
var someFormattedDate = y + '/' + dd + '/' + mm;
$scope.expireDateOptions.maxDate = someFormattedDate;
//code to set maxDates in Expire Date field -end
}
};
$scope.ChangeExpiryMinDate();
$scope.OpenAvailableDate = function() {
$scope.availableDatePopup.opened = !$scope.availableDatePopup.opened;
};
$scope.OpenExpireDate = function() {
$scope.expireDatePopup.opened = !$scope.expireDatePopup.opened;
};
}
]);
Below is the code i tried but not succeded.
var date = new Date(expiryMinDate);
var newdate = new Date(date);
newdate.setDate(newdate.getDate() + 3);
var dd = newdate.getDate();
var mm = newdate.getMonth() + 1;
var y = newdate.getFullYear();
var someFormattedDate = y + '/' + dd + '/' + mm;
$scope.expireDateOptions.maxDate = someFormattedDate;
Given your requirements, I have used the following to keep the minDate and maxDate set:
$scope.ChangeExpiryMinDate = function(availableDate) {
if (availableDate != null) {
var availableDate = new Date(availableDate);
var expiryMinDate = angular.copy(availableDate);
expiryMinDate.setDate(expiryMinDate.getDate() + 23);
$scope.ExpireDate = availableDate;
$scope.expireDateOptions.minDate = availableDate;
$scope.expireDateOptions.maxDate = expiryMinDate;
} else {
delete $scope.ExpireDate;
}
};
$scope.ChangeExpiryMinDate($scope.AvailableDate);
You forgot to pass the current AvailableDate into the function, so when controller first loads, the Expiry Date Field is already limited.
To disable weekends, you can update the ExpiryDate Options with:
$scope.expireDateOptions = {
formatYear: 'yy',
startingDay: 1,
minDate: today,
maxDate: "2017-06-12",
dateDisabled: function(data) {
var date = data.date;
var mode = data.mode;
return (mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ));
}
};
I have created a working JSFiddle here: https://jsfiddle.net/1ahyk735/
I'm new to nodejs and mongoose.
I have a database dated from 2009 until now and would like to count number of data of each month,
and return as json array. Slow async callback results all dates as Aug. 1, 2014
What is the proper way to implement this?
var dbURL = 'mongodb://localhost/database';
var db = require('mongoose').connect(dbURL);
var c_db = require('./models/models.js').c_db;
var start_date = new Date(2009,0,1);
end_date = new Date(2014,8,1),
next_date = new Date();
var test_json=[];
var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth());
var next_date = start_date;
for(var i=0;i<total_months;i++){
var firstDay = new Date(next_date.getFullYear(), next_date.getMonth(), 1);
var lastDay = new Date(next_date.getFullYear(), next_date.getMonth() + 1, 0);
next_date.setDate(lastDay.getDate()+1);
c_db.count({'shipdate':{'$gte':new Date(firstDay),'$lte':new Date(lastDay)}},function(err,query){
var item = {
"Date": firstDay,
"Count": query
}
test_json.push(item);
});
}
setTimeout(function(){
console.log(test_json);
},5000);
Be careful when you are writing javascript with async callbacks. What you want to do is to continue to the next item in the loop when the current async is finished. You can use a the "async" module: https://github.com/caolan/async
var async = require("async");
var dbURL = 'mongodb://localhost/database';
var db = require('mongoose').connect(dbURL);
var c_db = require('./models/models.js').c_db;
var start_date = new Date(2009,0,1);
end_date = new Date(2014,8,1),
next_date = new Date();
var test_json=[];
var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth());
var next_date = start_date;
async.timesSeries(total_months, function(n, next) {
var firstDay = new Date(next_date.getFullYear(), next_date.getMonth(), 1);
var lastDay = new Date(next_date.getFullYear(), next_date.getMonth() + 1, 0);
next_date.setDate(lastDay.getDate()+1);
c_db.count({'shipdate':{'$gte':new Date(firstDay),'$lte':new Date(lastDay)}},function(err,query){
var item = {
"Date": firstDay,
"Count": query
}
test_json.push(item);
next();
});
}, function(e) {
console.log(test_json);
});