Get the Dayname of string date js - javascript

Hi I am new to javascript I am trying to get the name of my date string
formatted dd/MM/yyyy
ex:
23/02/2019
expected output: Saturday
my code giving Nan. I will really appreciate any advice or help. Thank you
var ot="23/02/2019";
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date(ot);
var dayName = days[d.getDay()];
console.log(dayName);

Your new Date(ot) might be failing because of timezone issues. For safer side, you can break down your date string and pass it to new Date() as year, month, date.
JS months are index based so -1 from month in string
var ot="23/02/2019";
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var otArr = ot.split('/')
var d = new Date(otArr[2], otArr[1] - 1, otArr[0]);
var dayName = days[d.getDay()];
console.log(dayName);

Format to get a new date object with year , month and date is new Date(year,month,date);
To extract them seperately from the string date formatted (date/month/year) we need to split them by slash and provide the required parameters to the function as shown below.
var ot="23/02/2019";
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var splits = ot.split('/');
// var d = new Date(ot.split('/')[2],ot.split('/')[1] -1 ,ot.split('/')[0]);
var d = new Date(splits[2],splits[1] -1 ,splits[0]);
var dayName = days[d.getDay()];
console.log(dayName);

Related

retrieving day from the given date in string in javascript

I have this date in this format.
var str="2019-08-19";(year/month/date)
var parts =str.split('-');
var day =parseInt(parts[2],10);
I need to figure out as which day was 19th (Monday/Tuesday /...) .
What i tried doing was splitting the given date but that could only give the information such as 19 etc
You can simply do this
var d = new Date( "2019-08-19");
var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var n = weekday[d.getDay()];
Following example will help you.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date("2019-08-18");
var dayName = days[d.getDay()];
document.getElementById("myId").innerHTML = dayName;

Selected days random order, find the earliest and latest

I have got an array of days:
let days = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ]
Obviously the keys above are from 0 - 6. I use these days to generate a list, a user can then selecte and deselect days from this list. So if they deselect Monday and then select Sunday I now have a selected array:
let selected = [ 'sunday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ]
I then want to format the selected dates and display it to the user, but of course using the code below I will get Sunday - Saturday, when really I want Tuesday - Sunday.
let dayOne = this.selected[0];
let dayTwo = this.selected[this.selected.length - 1];
if (dayOne === undefined && dayTwo === undefined) return;
return dayOne.charAt(0).toUpperCase() + dayOne.slice(1) + ' - ' + dayTwo.charAt(0).toUpperCase() + dayTwo.slice(1);
What's a nice and clear way to do this?
My recommendation:
Use a simple integer list [0...6] and use that instead. I'm pretty sure you have 7 checkboxes holding the weekday names as values. Use the numbers as values instead.
Then, when you need the array with day names, do this:
const weekdays = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ];
let selected = [5,2,4,1]; //unsorted array
selected.sort(); //careful here
let selecteddays = selected.map(d => weekdays[d]);
console.log(selecteddays);
This sort() can be problematic, gotta be careful with it.
Check this on how to properly sort numeric arrays: How to sort an array of integers correctly
You can sort by comparing the index in original days array
let days = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ]
let selected = ['saturday', 'friday', 'wednesday']
selected.sort((a,b) => days.indexOf(a) - days.indexOf(b))
console.log(selected)

JS dates, first day of the month

i'm programming a calendar and i need to know what the first day of each month is. Like, This month, hte first day was on a sunday. How would i go about to figure that out for all months of the year? Or any month for that matter.
Thanks in advance!
edit: the day can be returned as an integer.
Where options for toLocaleString are supported, you can use it to get the day name in the browser default language:
function getDayName(date) {
return date.toLocaleString(undefined, {weekday:'long'});
}
function getMonthName(date) {
return date.toLocaleString(undefined, {month:'long'});
}
// Create a date
var d = new Date();
// Set to first of month
d.setDate(1);
// Create string
console.log(`The first of ${getMonthName(d)} was a ${getDayName(d)}.`);
Of course mixing English with some other language may not be appropriateā€¦
You could create a method that returns the day name
function(year, month){
var date = new Date(year, month, 1);
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
return days[date.getDay()];
}
JavaScript already provides this out of the box be using getDay.
new Date().getDay()
This will return 0-6. Depends on what weekday it is.
If you need it as a readable string you may want to do something like this:
var weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
console.log(weekdays[new Date().getDay()]);
Knowing this you can go furter:
const year = new Date().getFullYear();
const weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
[0,1,2,3,4,5,6,7,8,9,10,11].forEach(x => {
const weekday = new Date(year, x, 1).getDay();
console.log(weekdays[weekday]);
});
See: MDN
I would highly recommend using MomentJS library if you are not already using it. Using moment, you can get the day of 1st of any month using this single statement:
moment("2017-11-01").startOf('month').format("dddd")
If you cannot use moment for some reason, then you could just create a function that takes in month and year and returns back the day of 1st of that month. You need to use Date.prototype.getDay() for this, which returns a value from 0 to 6, where 0 means Sunday.
$("#get-day").on("click", function(e){
var year = $("#year").val();
var month = $("#month").val();
alert( getDay(year, month) );
});//#get-day click()
function getDay(year, month){
var days = ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"];
var dayIndex = new Date(year + "-" + month + "-01").getDay();
return days[ dayIndex ];
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="year" value="2017" />
<input type="text" id="month" value="10" />
<button id="get-day">Get Day on 1st</button>
The .getDay() method returns an integer, the day of the week for the specified date according to local time, where Sunday = 0 and Saturday = 6. Here's an example using this:
dateFunction = function(myDate){
var days =
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
var dayInt = new Date(myDate).getDay()
return days[dayInt]
}
var FirstDayOfOctober = dateFunction("2017-10-01");

how to use for of loop, resulting an array as an output

I want to capitalize the days in the array named 'days' and get the result in an array form only by calling 'console.log(days)'
Please see below :
Can anybody help me finish up code in the the block of for of loop?
edit(summary) :
I questioned this to know the reason why the value of the each 'day' does not get changed in this case. and Suren Srapyan has provided a great answer to this :
'You are getting the copy of each item in the loop. So day is only a copy of the item's value and changing it to have another value will not change the item in the array.'
let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
for (day of days) {
day = day[0].toUpperCase() + day.slice(1);
// your code goes here
}
console.log(days);
for of is not like to any simple loop. Under it is another construction.
You are getting the copy of each item in the loop. So day is only a copy of the item's value and changing it to have another value will not change the item in the array.
Here is what going under the for of loop.
let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
const iterator = days[Symbol.iterator]();
let item = iterator.next();
while(!item.done) {
console.log(item.value);
item = iterator.next();
}
Above code shows that for of loop is only for readonly purposes
You can use Array#map function for it
let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
days = days.map(day => day[0].toUpperCase() + day.slice(1));
console.log(days);
You can also use forEach loop to do the task.
days.forEach(function(item, index, array) {
array[index] = item[0].toUpperCase() + item.slice(1)
});
console.log(days);
you can also use reduce method of array
let days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
let result = days.reduce((r,a)=>r.concat(a.charAt(0).toLocaleUpperCase()+a.slice(1)),[]);
console.log(result)
Try this one and I think It will help
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
for (let day of days){
let firstLetter= day.substr(0,1)
let otherLetters=day.substr(1)
console.log(firstLetter.toUpperCase().concat(otherLetters));
}

Javascript join() array

This might be very simple but I am trying to use the join() array in order to remove the - from the last item on the days array.
How can I do that? This is my code:
var days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
];
var counter = 0;
while (counter < days.length) {
document.write(days[counter]);
counter++;
days.join(' - ');
}
You don't need a loop. It's very simple:
var days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
];
document.write(days.join(", "));
I don't recommend the use of document.write. It's dangerous. Use DOM methods instead:
document.getElementById("layer").innerHTML = days.join(", ");
And the HTML as simple as this:
<div id="layer"></div>

Categories