Javascript get month range by month name - javascript

I have a jQuery onclick function which basically receives a month name, and from that month name, I would like to get a month range. Like for instance I'm passing a month name "May" like this:
$('#swiperNext').click(function(e)
{
var currentMonth = $('.swiper-slide-active h3').html();
console.log(currentMonth);
});
Now I'd like to pass the current month name to a JS function and get date range for that month.
So for example May would be => 01-05-2016 - 31-05-2016, so on and so on... Can someone help me out with this ?

You can do it without any third party library like this.
I presume you are calculation for current year
var date = new Date();
var y = date.getFullYear();
var month = $('.swiper-slide-active h3').text();
var m = new Date(Date.parse(month, 1, " + y)).getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
EDIT: I have changed the answer to use a month name as a string

I would use Moment.js. It is perfect for manipulating dates and do all sorts of things.
In your specific case:
var startOfMonth = moment().month("June").startOf("month").toDate()
var endOfMonth = moment().month("June").endOf("month").toDate()

You can use this function:
function getMonthFromString(monthName){
var date = new Date(Date.parse(monthName + 1, new Date().getFullYear()));
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1).getDate();
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
var month = new Date(Date.parse(monthName + 1, new Date().getFullYear())).getMonth()+1;
var year = new Date().getFullYear();
return firstDay + "-" + month + "-" + year + " - " + lastDay + "-" + month + "-" + year;
}

First I create month name array according as getMonth() index.Then find wanted month name by indexOf ,that will return your array index when found it.
Note getMonth() is only return number between 0 and 11 assume Jan to Dec
So added 1 in getMonth
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
$('#swiperNext').click(function(e)
{
var currentMonth = $('.swiper-slide-active h3').html();
var month = monthNames.indexOf(currentMonth);
var d = new Date();
var start = new Date(d.getFullYear(),month,1);
var end = new Date(d.getFullYear(),month+1,0);
var startdate = start.getDate()+"/"+(start.getMonth()+1)+"/"+start.getFullYear();
var enddate = end.getDate()+"/"+(end.getMonth()+1)+"/"+end.getFullYear();
console.log(startdate+"-"+enddate);
});

Related

why the javascript did not get the right day [duplicate]

I have such javascript code
alert(DATE.value);
var d = new Date(DATE.value);
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDay();
alert(month);
alert(day);
if(2012 < year < 1971 | 1 > month+1 > 12 | 0 >day > 31){
alert(errorDate);
DATE.focus();
return false;
}
take for instance: DATE.value = "11/11/1991"
when I call alert(day); it shows me 3;
when I call alert(d); it is returns me correct info.
use .getDate instead of .getDay.
The value returned by getDay is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.
getDay() returns the day of the week. You can however use the getDate() method.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getDay
getDay() will give you the day of the week. You are looking for getDate().
I had a similar problem. date.getMonth() returns an index ranging from 0 to 11. January is 0. If you create a new date()-object and you want to get information about a costum date not the current one you have to decrease only the month by 1.
Like this:
function getDayName () {
var year = 2016;
var month = 4;
var day = 11;
var date = new Date(year, month-1, day);
var weekday = new Array("sunday", "monday", "tuesday", "wednesday",
"thursday", "friday", "saturday");
return weekday[date.getDay()];
}
From now on you probably want to use the following below functions for Date objects:
function dayOf(date)
{
return date.getDate();
}
function monthOf(date)
{
return date.getMonth() + 1;
}
function yearOf(date)
{
return date.getYear() + 1900;
}
function weekDayOf(date)
{
return date.getDay() + 1;
}
var date = new Date("5/15/2020");
console.log("Day: " + dayOf(date));
console.log("Month: " + monthOf(date));
console.log("Year: " + yearOf(date));
function formatDate(date, callback)
{
var weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var day = weekday[date.getDay()];
console.log('day',day);
var d = date.getDate();
var hours = date.getHours();
ampmSwitch = (hours > 12) ? "PM" : "AM";
if (hours > 12) {
hours -= 12;
}
else if (hours === 0) {
hours = 12;
}
var m = date.getMinutes();
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var month = months[date.getMonth()];
var year = date.getFullYear();
newdate = day + ', ' + month + ' ' + d + ',' + year + ' at ' + hours + ":" + m + " " + ampmSwitch
callback(newdate)
}
and call with this code
date="Fri Aug 26 2016 18:06:01 GMT+0530 (India Standard Time)"
formatDate(date,function(result){
console.log('Date=',result);
});
When you use the function .getDay(), this one consider the month's number start in 0 and not in 1, then if you use the date new Date(2021-11-04), the .getDay() function will consider the day 4 of dezember and not november...
Then, to get de day 4 of november, you need pass "2021-10-04" to the Date() class.
It may also be an issue with the technology used and the browser ES5 compatible.
I had such a problem while developing an application in react native.
return `${date.getDay()} ${month}, ${date.getFullYear()}`;
to
return `${date.getDate()} ${month}, ${date.getFullYear()}`;

Javascript Countdown Date

probably an easy question for many of you. :)
I'm trying to use the simple counter from this countdown: https://github.com/rendro/countdown and i'm stuck passing javascript variable.
Normally the end date format for this counter is:
var endDate = "June 7, 2087 15:03:25";
then in the function you pass the variable:
$('.countdown.simple').countdown({ date: endDate });
but i'm trying to get a dynamic 24h date and time and sending the output in the same original endDate format. The goal is to have a countdown purchased timer to purchase this product before the end of the day so (time now - and of the day). Unfortunately its not working.
<script type="text/javascript">
var dateNow = new Date();
var monthsArray = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
var monthNow = monthsArray[dateNow.getMonth()];
var dayNow = dateNow.getDate();
var yearNow = dateNow.getFullYear();
var hourNow = dateNow.getHours();
var minNow = dateNow.getMinutes();
var secNow = dateNow.getSeconds();
var completeDate = monthNow + " " + dayNow + ", " + yearNow + " " + hourNow + ":" + minNow + ":" + secNow;
$(function() {
$('.countdown.simple').countdown({ date: completeDate });
});
alert(completeDate);
</script>
i have set an alert to test the output format and its working well. But my counter is showing 0 years, 0 days, 00 hours, 00 min and 00 sec.
whats wrong..
You are setting the end date for the countdown timer to the present date. You need to pass in a future date.
Instead of creating a date string, you can also just pass in a date object.
Example
// Create the date object
var completeDate = new Date();
// Set the date to the last possible second of the day
completeDate.setHours(23, 59, 59);
// Start the timer
$(function() {
$('.countdown.simple').countdown({ date: completeDate });
});

Edit JavaScript (Tomorrow's date)

I am trying to edit some JavaScript code which basically shows tomorrow's date. However for Friday and weekends (Friday, Saturday and Sunday) it should show the following Monday's date.
Here is the code I have:
var date = new Date(); // timezone
date.setDate(date.getDate() + 1); // move to tomorrow
date.setUTCHours(11,0,0,0); // set time using UTC(GMT) timezone
document.getElementById("next-shipment").textContent = date.toLocaleString();
JSFiddle
For example let say today is Tuesday, November 4, 2015. The javascript code should show "November 5, 2015"---> in this format.
On Friday, Saturday,and Sunday the code should show: Next Monday's date: November 9, 2015
The code should work all year around.
Try this:
var today = new Date(); // timezone
document.getElementById("result").innerHTML = "<br/>Today's next day is: " + FormatDate(GetNextDay(today));
function GetNextDay(date){
date.setDate(date.getDate() + 1); // move to next day.
switch(date.getDay()) {
case 0: //Sunday
case 6: //Saturday
date = GetNextDay(date);
}
return date;
}
function FormatDate(date){
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
return months[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear();
}
function TestDate(){
var date = new Date(document.getElementById("TestDate").value);
document.getElementById("result").innerHTML += "<br/>Selected day's next day is: " + FormatDate(GetNextDay(date));
}
<input type="text" id="TestDate" value="November 06, 2015" />
<input type="button" value="Get Next Day" onclick="TestDate();" />
<div id="result"></div>
The idea is fairly simple:
The first two lines and the TestDate() function at the end are only for testing and you don't need them in your code.
The job is mainly done by the GetNextDay() function. You give it a date and it calculates and give you back the next date (skipping the weekend). It does that in two steps:
1- First it adds one day to the given date date.setDate(date.getDate() + 1);.
2- It checks the day of the new date date.getDay(). If it is 6 or 0 (Saturday or Sunday) it calls itself again date = GetNextDay(date); which means it will add one more day to the date. This concept of a function calling itself is called "recursion" in programming. When it reaches Monday, it will stop calling itself and return the date.
The only way to calculate the next day properly is by adding one day to the date. This utilizes JavaScript's Date library which knows how to do the calculation. For example, it knows that adding one day to "November 30" is "December 1", NOT "November 31". If we try to do that manually by adding 1 to number of the day: 30 + 1 = 31, but "November 31" is not a valid date. To solve this issue, we will need to write a library similar to the one that JavaScript has. Obviously, this is like reinventing the wheel and there is no point in that.
The Date constructor also has a function called getDay() which returns a integer between 0 and 6 (0 = Sunday, 6 = Saturday). You can use this to detect Friday(0), Saturday(6), Sunday(0) and omit them.
Here is a demo that alerts you if it's the weekend:
var myDate = new Date();
myDate.setFullYear(2015);
myDate.setMonth(11);
myDate.setDate(6);
if(myDate.getDate() == 5 || myDate.getDay() == 6 || myDate.getDay() == 0) alert('Weekend!');
document.write(myDate);
To find the next day, pass the Date constructor a time & it will do the work for you. You will need to create an array however to format it in the way you want November, 5 2015.
JS:
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var tomDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var day = tomDate.getDate();
var month = monthNames[tomDate.getMonth()];
var year = tomDate.getFullYear()
var d = new Date();
var n = d.getDay();
if(n == 5){
var fromFri = n + 4;
document.write("<b>" + month + " " + fromFri + ", " + year + "</b>");
}else if (n == 6){
var fromSat = n + 3;
document.write("<b>" + month + " " + fromSat + ", " + year + "</b>");
}else if (n == 0) {
var fromSun = n + 2;
document.write("<b>" + month + " " + fromSun + ", " + year + "</b>");
}else{
document.write("<b>" + month + " " + day + ", " + year + "</b>");
}
Updated: CODEPEN DEMO

Converting date from variable to MM-DD-YYY [duplicate]

This question already has answers here:
How do I format a Javascript Date?
(11 answers)
Closed 8 years ago.
I have a function that takes an input and converts it to a date. I would like to get the date in the format January 01, 2014. The #date comes in with the form as January 10 - January 25. I need to split these into two different dates (the start date and the end date). The #year comes in as 2014
Not very experienced with JavaScript but trying to get this to work.
Here is my script:
$(function () {
$('#submit').click(function (event) {
event.preventDefault();
var startDates = $('#date').val().split(" - ");
var year = $('#year').val();
var yearDec = parseInt(year, 10) + 1;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + yearDec;
var startDate = Date.parse(payPdStart);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate); })
})
The script outputs something like... Thu Dec 25 2014 00:00:00 GMT-0500 (Eastern Standard Time)
I want it to show Thursday Dec 25, 2014 ( I don't need any time portion)
You could
use the methods of the Date-object: http://www.w3schools.com/jsref/jsref_obj_date.asp
use Moment.js: http://momentjs.com/. It's a js-library that provides methods for parsing, manipulating and formatting dates
use jQuery-Datepicker: http://api.jqueryui.com/datepicker/ for the whole task
This should work for what you are doing with the Moment.js library
<script>
$(function () {
$('#submit').click(function (event) {
event.preventDefault();
var startDates = $('#date').val().split(" - ");
var year = $('#year').val();
var payPdStart = startDates[0] + ' '+ year;
var payPdEnd = startDates[1] + ' ' + year;
var startDate = Date.parse(payPdStart);
myStartDates = moment(new Date(startDate)).format('MMMM DD, YYYY');
var endDate = Date.parse(payPdEnd);
myEndDates = moment(new Date(endDate)).format('MMMM DD, YYYY');
})
})
</script>
"July, 03 2014"
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
Number.prototype.pad = function() {
return (this < 10) ? ("0" + this) : this;
}
var d = new Date(),
h = monthNames[d.getMonth()] + " " + d.getDay().pad() + ", " + d.getFullYear();

"reset date value in Javascript"?

How to "reset date value in Javascript" everytime the div in html is clicked? I am trying to make a basic delivery calculation date based from today's date, for example, 3 days delivery date from today(let say today is 5 November 2011). When user click on it, it must show the delivery date will be on Tuesday 8 November 2011, but when user click on it again, the second time, today's date has changed to be based on 8 November 2011 instead of 5. How to reset/clear the "Today" variable to be based on today's date?
How to display day in Monday, Tuesday, Wednesday, and so on instead of 1,2,3,4,5,6,7?
My current code is
$(document).ready(function() {
var Today = new Date();
var NumDelivery = 0;
function Calculate() {
var days = Today.getDay();
var dd = Today.getDate();
var mm = Today.getMonth() + 1;
var y = Today.getFullYear();
var FormattedDate = days + ',' + dd + '-'+ mm + '-'+ y;
Today.setDate(Today.getDate() + NumDelivery);
$('#DateDelivery').text(FormattedDate);
}
Umm, how about simply use NewDate = new Date() and then instead of Today.setDate(...) use NewDate.setDate(...)
As for day names you can use an array like this :
var d = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
dayName = d[NewDate.getDay()];
Just move the var Today = new Date() into the function Calculate
$(document).ready(function() {
var NumDelivery = 0;
var DAYS_OF_WEEK = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat' ];
function Calculate() {
var Today = new Date();
var days = Today.getDay();
var dd = Today.getDate();
var mm = Today.getMonth() + 1;
var y = Today.getFullYear();
var FormattedDate = DAYS_OF_WEEK[days] + ',' + dd + '-'+ mm + '-'+ y;
Today.setDate(Today.getDate() + NumDelivery);
$('#DateDelivery').text(FormattedDate);
}
I displayed the day of week name using an array.

Categories

Resources