How to turn a period of date into an array? - javascript

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) );

Related

Always display 2 digits for date/time with `getDate`

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);

Add days number to string Javascript

I'm looking to add 5 days to the date however because I need a date as dd mmm yy the date has to be a string. The string part works great but as soon as I add anything to the new date value it then doesn't increment the month. Adding any later infers the number as a string.
Thanks
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const dateObj = new Date();
const month = monthNames[dateObj.getMonth()];
const day = String(dateObj.getDate()).padStart(2, '0');
const year = dateObj.getFullYear();
const output = + day +'\n'+ month + '\n' + year;
document.write(output)
You can use setDate() to add days to your date. Then you can use toLocaleDateString() to format your date.
const addDays = (days) => {
const date = new Date();
date.setDate(date.getDate() + days);
return date.toLocaleDateString(undefined, {
day: '2-digit',
month: 'short',
year: 'numeric'
});
}
console.log(addDays(5));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Block a specific date on a Javascript date selector

I would like to request assistance on how can I block a specific dates on my date selector.
Specific dates are:
December 24, 25, 30, 31 - 2020 and January 1, 2021 ONLY.
Note: We need to remain the current function where the selected available dates are 2 days advanced from today. Weekends are also blocked. This functions are already in the script
<style>
select {
font-family:Arial, Helvetica, sans-serif;
font-size:14px; color:#000;
}
</style>
<select name="APPOINTMENTDATE" id="date-range" data-field-type="Text">
<option value="" selected="selected">Select date</option>
</select>
<script>
var dateRange = document.getElementById('date-range'),
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
for(var day = 2; day < 30; day++) {
var date = new Date();
date.setDate(date.getDate() + day);
if(!(date.getDay()==6|| date.getDay()==0))
dateRange.options[dateRange.options.length] = new Option([monthNames[date.getMonth()], date.getDate(), date.getFullYear()].join(' '));
}
</script>
You can do something like this.
var dateRange = document.getElementById('date-range'),
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
for (var day = 2; day < 30; day++) {
var date = new Date();
date.setDate(date.getDate() + day);
if (!(date.getDay() == 6 || date.getDay() == 0)) {
dateRange.options[dateRange.options.length] = new Option(
[monthNames[date.getMonth()],
date.getDate(),
date.getFullYear()
].join(' '));
}
}
//define dates to be blocked.
var arr = ["Dec 24 2020", "Dec 25 2020", "Dec 30 2020", "Dec 31 2020", "Jan 01 2021"];
//loop through dateRange.options
for (var i = 1; i < dateRange.options.length; i++) {
//when date to be blocked found, mark it as disabled
arr.includes(dateRange.options[i].value) ? dateRange.options[i].disabled = true : dateRange.options[i].disabled = false;
}

Convert IST date format to YYYY-MM-DD in javascript

I'm getting a date string "Wed Mar 19 00:30:00 IST 1997" and I want to make this as readable YYYY-MM-DD format. Is there any solution to do this with pure javascript?
It seems that your time is not normal javascript date string. if you remove the IST from your string, you can create a date object from it.
dateString = 'Wed Mar 19 00:30:00 IST 1997';
var date = new Date(dateString.replace('IST', ''));
let day = date.getDate();
let month = date.getMonth()+1;
let year = date.getFullYear();
console.log(year+"/"+month+"/"+day)
You can try using the following function
let str = "Wed Mar 19 00:30:00 IST 1997"
function formatDate(date) {
date = date.split(" ");
let monthsList = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
let year = date[5];
let month = `0${(monthsList.indexOf(date[1]) + 1)}`.slice(-2);
let day = date[2];
return `${year}-${month}-${day}`;
}
console.log(formatDate(str));
you can try this.
let date = new Date();
let day = date.getDate();
let month = date.getMonth()+1;
let year = date.getFullYear();
console.log(year+"/"+month+"/"+day)

get current date in this format "May 09, 2019"

i want to get the current time in May 09, 2019 format.
var d = new Date();
var delay = 500;
var month = d.getMonth()+1;
var day = d.getDate();
var y=d.getFullYear();
var output = d.getFullYear() + '/' +
((''+month).length<2 ? '0' : '') + month + '/' +
((''+day).length<2 ? '0' : '') + day;
here the output shows the current time in 2019/05/09 format.how should i get "May 05, 2019" format.
Try this
var d = new Date();
var months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
var month = months[d.getMonth()]
var day = d.getDate();
var y=d.getFullYear();
var today = month +" " +day + "," + y;
console.log(today);
Instead of creating (and maintain) your own array of names you can use the following:
d.toLocaleString('en-us', { month: 'long' });
var d = new Date();
var month = d.toLocaleString('en-us', { month: 'long' });
var day = d.getDate();
var y=d.getFullYear();
var today = month +" " +day + "," + y;
console.log(today);
You can do this,
var monthNames = [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct",
"Nov", "Dec"
];
var d = new Date();
var day = d.getDate();
var monthIndex = d.getMonth();
var year = d.getFullYear();
var output = monthNames[monthIndex] + ' 'day + ' ,' + year;
This is exactly what you are looking for
function LogCurrentDate(e){
var date = new Date();
var options = { year: 'numeric', month: 'long', day: '2-digit' };
$(".output").empty().append("<p>" + date.toLocaleDateString('en-US', options) + "</p>");
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button onclick="LogCurrentDate(event)">Show Date</button>
</div>
<div class="output"></div>

Categories

Resources