How to get month name from an html Date input value? - javascript

This is the date input
<input id="customer-date" name="customer-date" type="date" required>
and this is the script
const customerDate = document.getElementById('customer-date').value;
const dateHandler = document.getElementById('date-handler');
dateHandler.innerHTML = customerDate;
But when I pick a date, the value I get to display in dateHandler is formatted like 2017-11-22 the problem is that the format="dd/MM/yyyy" attribute doesn't make it consistent between days and months when displaying and its obviously confusing. So I want to get the month name from the picked date to display it such 2017-November-22. Any ideas?

If you were looking to just get the month name from the month number, you could use this:
var str = "2017-11-22"; // this would be your date
var res = str.split("-"); // turn the date into a list format (Split by / if needed)
var months = ["Jan", "Feb", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
console.log(months[res[1]-1]) // month name
JSFiddle: https://jsfiddle.net/p8fwhydc/1/

When reformatting a date string, you should always consider just reformatting the string and avoiding Date objects altogether, as for Noy's answer.
However, you can also use some Date object features if you take precautions to avoid the pitfalls of parsing and formatting.
This type of question is two questions in one:
How do I parse the string to a Date
How do I format the date
In the first case, a date format of YYYY-MM-DD should be parsed as UTC (some browsers may not) so you should parse that manually.
The second part is to generate a formatted string, you can leverage the Intl object where supported to get the string in the host default language, e.g.
// Parse string in YYYY-MM-DD format as local
function parseYMD(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2]);
}
// Format Date as D-MMMM-YYYY using host default language for month name
function formatDMMMMY(date) {
function z(n){return (n<10?'0':'') + n}
return date.getFullYear() + '-' +
date.toLocaleString(undefined, {month:'long'}) + '-' +
z(date.getDate());
}
var s = '2017-11-22';
console.log(parseYMD(s).toString());
console.log(formatDMMMMY(parseYMD(s)));

You can use the Date() javascript function like :
Date.prototype.getFullDate = function() {
return this.getFullYear() + '-' + this.toLocaleString(undefined, {month:'long'}) + '-' + this.getDate();
}
const dateStr = document.getElementById('customer-date').value.split('/');
var date = new Date(dateStr[2], dateStr[1], dateStr[0]);
document.getElementById('date-handler').innerHTML = date.getFullDate();

Here's the simple solution I made , I hope that helps you
function showdate() {
var customerDate = document.getElementById('customer-date').value;
var dateHandler = document.getElementById('date-handler');
dateHandler.innerHTML = customerDate;
var months = new Array();
months[0] = "January";
months[1] = "February";
months[2] = "March";
months[3] = "April";
months[4] = "May";
months[5] = "June";
months[6] = "July";
months[7] = "August";
months[8] = "September";
months[9] = "October";
months[10] = "November";
months[11] = "December";
var date = new Date(customerDate);
var month = months[date.getMonth()];
//converting the date into array
var dateArr = customerDate.split("-");
//setting up the new date form
var forDate = dateArr[0] + "-" + month + "-" + dateArr[2];
document.getElementById("new-date-handler").innerHTML = forDate;
}
<input id="customer-date" name="customer-date" type="date" required>
<input type=button value=validate onclick="showdate()">
<p id="date-handler"></p>
<p id="new-date-handler"></p>

Related

Dates sum are not consistent [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 5 months ago.
I have a problem when summing dates in JavaScript. When I run a function to write the current month and the following 12 months, I can see that it retrieves all the month/year dates correct (I also added the number of days of each month).
But after, on changing the selection of the month, I want to display the number of days of the selected month. When I select Feb2022 it gives me 29 days, when actually it has 28 days (also written in the selection option)
How can JavaScript give me unconsistent values for similar functions?
//const today = new Date();
const monthNames = ["January","February","March","April","May","June","July","August","September","October","November","December"];
function writemonth(x) {
var text = "";
var today = new Date();
var dateObj = new Date(today.getFullYear(), today.getMonth()+x, 0);
var tdays = dateObj.getDate();
return tdays;
}
function writemonths() {
var text = "";
var today = new Date();
for (let i = 1; i <= 12; i++) {
var dateObj = new Date(today.getFullYear(), today.getMonth()+i, 0);
var monthNumber = dateObj.getMonth();
var year = dateObj.getFullYear();
var tdays = dateObj.getDate();
var monthName = monthNames[monthNumber];
text += "<option value='"+i+"'>" + monthName + " " + year +" " + tdays +"</option>";
}
return text;
}
//Let's start by writing the basic layout elements
document.getElementById("availability-calendar").innerHTML = "<select id='months' onchange='refresh();'><option value='0'>Loading...</option></select><div id='month'>"+writemonth(1)+"</div>";
document.getElementById("months").innerHTML = writemonths();
function refresh() {
var e = document.getElementById("months").value;
alert(e);
document.getElementById("month").innerHTML = writemonth(e);
}
<div id="availability-calendar"></div>
Its the issue with the writemonth function.
Expression var dateObj = new Date(today.getFullYear(), today.getMonth() + x, 0); is making string concatenation at today.getMonth() + x because today.getMonth() is a number and x is a string. On addition this will perform string concatenation. To fix this you have to convert x to number before addition, just by adding a + symbol in fromt of x like
var dateObj = new Date(today.getFullYear(), today.getMonth() + +x, 0);
Working fiddle
//const today = new Date();
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function writemonth(x) {
var text = "";
var today = new Date();
var dateObj = new Date(today.getFullYear(), today.getMonth() + +x, 0);
var tdays = dateObj.getDate();
return tdays;
}
function writemonths() {
var text = "";
var today = new Date();
for (let i = 1; i <= 12; i++) {
var dateObj = new Date(today.getFullYear(), today.getMonth() + i, 0);
var monthNumber = dateObj.getMonth();
var year = dateObj.getFullYear();
var tdays = dateObj.getDate();
var monthName = monthNames[monthNumber];
text += "<option value='" + i + "'>" + monthName + " " + year + " " + tdays + "</option>";
}
return text;
}
//Let's start by writing the basic layout elements
document.getElementById("availability-calendar").innerHTML = "<select id='months' onchange='refresh();'><option value='0'>Loading...</option></select><div id='month'>" + writemonth(1) + "</div>";
document.getElementById("months").innerHTML = writemonths();
function refresh() {
var e = document.getElementById("months").value;
// alert(e);
console.log(e);
document.getElementById("month").innerHTML = writemonth(e);
}
<div id="availability-calendar"></div>
Digging a little deeper into your issue
Your function writemonth is recieving parameters as string. Because you have provided the value of each option as a string inside the function writemonths with below statement
text += "<option value='" + i + "'>" + monthName + " " + year + " " + tdays + "</option>"
So inside your writemonth function the value for each option will be recieved as a string. So the expression today.getMonth() + x provides string as the result.
The issue is not just with February option. The year is generated wrong for all options. In case of February option, the writemonth function recieves parameter as "6". So the expression today.getMonth() + x will provide "86" as the result.
Because todays month september returns getMonth() result 8 (As of today 13-September-2021 on which answer was posted). So the expression var dateObj = new Date(today.getFullYear(), today.getMonth() + x, 0); will return a date February 29 2028.
This is because the month value "86" adds 7 years to the year because 86/12 gives quotient than 7 and reminder 2. So all the result generated will be 7 years ahead. For 2028, Febrary has 29 days and all other months days wont varry. Because here only the year is getting incremented by 7, not the month.
Please see the value of date in the below fiddle. A little surprised with the year?
function writemonth(x) {
var text = "";
var today = new Date();
var dateObj = new Date(today.getFullYear(), today.getMonth() + x, 0);
console.log(dateObj);
var tdays = dateObj.getDate();
return tdays;
}
writemonth("6")
+ Symbol is multitasking
Adding a number to a number with + generate a number as the result.
Example
const num1 = 10;
const num2 = 20;
const result = num1 + num2;
console.log(result);
console.log(typeof result);
Adding a string to another string with + will generate a string as the result.
Example
const str1 = "John";
const str2 = "Doe";
const result = str1 + str2;
console.log(result);
console.log(typeof result);
If a number is added to a string with +, then JavaScript provides a string as the response.
In JavaScript, the + operator is used for both numeric addition and
string concatenation. When you "add" a number to a string the
interpreter converts your number to a string and concatenates both
together.
Example
const num1 = 10;
const str1 = "Name";
const result = num1 + str1;
console.log(result);
console.log(typeof result);

Splitting date in Javascript

var date = "1st December,2016"
How can I split this string to get date,month and year?
I am doing date.split(" ",1) then I am getting output as "1st". Now how to get December and 2016?
If you could make sure that your string always has that format, the simplest way is to use 2 split command:
var date = "1st December,2016";
var arr1 = date.split(' ');
var arr2 = arr1[1].split(',');
console.log('date: ', arr1[0]);
console.log('month: ', arr2[0]);
console.log('year: ', arr2[1]);
Update: I just realize split could be used with Regex, so you could use this code too:
var date = '1st December,2016';
var arr = date.split(/ |,/);
console.log('date: ', arr[0]);
console.log('month: ', arr[1]);
console.log('year: ', arr[2]);
Use Regular Expression for that,
function ShowDateParts()
{
var regex =/\s|,/g;
fullDate = "1st December,2016";
var dateParts =fullDate.split(/[\s|,]/g);
alert("date : "+ dateParts[0] + " Month : " +dateParts[01] + " Year : " + dateParts[02]);
}
Instead of
date.split(" ",1)
Just use
var dateparts = date.split(" ");
And then access each part as an array element.
var day=dateparts [0];
var month=dateparts [1].slice(0, -1);
var year=dateparts [2];
I would create a date object out of my string value and use is to get all values.
Example Snippet:
var date = "1st December,2016";
//reftor to valid date
var validDate = date.replace(/(st)/, '');
//create date object
var dateObj = new Date(validDate);
//get any value you need
console.log(dateObj.getDate());
console.log(dateObj.getMonth());
Update:
Snippet to get intended output: (get month as string)
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var date = "1st December,2016";
//reftor to valid date
var validDate = date.replace(/(st)/, '');
//create date object
var dateObj = new Date(validDate);
//get any value you need
console.log(dateObj.getDate());
console.log(monthNames[dateObj.getMonth()]);
console.log(dateObj.getFullYear());
var date = "1st December,2016";
var dataArray = date.split(/[ ,]/);
console.log('Day:' + dataArray[0]);
console.log('Month:' + dataArray[1]);
console.log('Year:' + dataArray[2]);

how to get the date into string format by passing date like-01/09/2016

I want to convert Date to string format with the day name and month name like ,if am passing date like 01/09/2016 then it should be got render like day name of 1st September like Thursday 01,September 2016,the toughest task is to get day name of date.so how can i achieve this?
You can do that very easily with JavaScript. Try the following snippet:
var d = new Date("2016-09-01");
console.log(d.toDateString());
The output is:
Thu Sep 01 2016
you can try this
<script>
function myFunction() {
var s = '2016/09/01';//this may be user entered string
var d = new Date(s);
var n = d.toString();
console.log(n);
}
</script>
The format that you require dd/mm/yyyy is not natively supported you need to use something like momentjs to parse various different formats and then you can use toString as suggested
javascript native date object can be constructed from string date. But it support 'mm/dd/yyyy' format. So first convert your date format in 'mm/dd/yyyy' format. Then you can construct javascript date object. After that you can use getDay and getMonth function to get day of week and month.
function getDayOfDate (date){
var arr = date.split('/');
var newFormat=arr[1]+"/"+arr[0]+"/"+arr[2];
var date = new Date(newFormat);
return date.getDay();
}
the above function will return value from 0-6. You can use switch case to print day of week.
The following re-tunes Thursday 1 September 2016 when the following string is passed '2016-09-01'.
Please note the full name of the week Thursday is returned and not only and abbreviation like Thu;
(function() {
var dateFormat = function(ourDate) {
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
date = new Date(ourDate),
year = date.getFullYear(),
indexMonth = date.getMonth(),
dayWeek = date.getDay(),
day = date.getDate();
return weekDays[dayWeek] + ' ' + day + ' ' + months[indexMonth] + ' ' + year;
};
console.log(dateFormat('2016-09-01'));
})();
You can extend the datetime
Date.prototype.Format = function() {
var weekday = new Array(7);
weekday[0]= "Sunday ";
weekday[1] = "Monday ";
weekday[2] = "Tuesday ";
weekday[3] = "Wednesday ";
weekday[4] = "Thursday ";
weekday[5] = "Friday ";
weekday[6] = "Saturday ";
var weekday = weekday[this.getDay()];
var day = this.getDay();
if(day === 1)
day += day + "st"
else day+= "th"
var months = new Array(12);
months[0]= " January ";
months[1] = " February ";
months[2] = " Mars ";
months[3] = " April";
months[4] = " May ";
months[5] = " June ";
months[6] = " July ";
months[7] = " August ";
months[8] = " September ";
months[9] = " October ";
months[10] = " November ";
months[11] = " December ";
var month = months[this.getMonth()]
return weekday + day + month + this.getFullYear();
};
var d = new Date();
console.log(d.Format());
Using below code, you get date string as you mentioned.
in some cases, you get previous date than the date you entered in the var d = new Date("2016-09-01"); is due to Eastern Daylight Time.
so , this how you get exact date string format `enter code
var doo = new Date("2011-09-24");
console.log(new Date(doo.getTime() + doo.getTimezoneOffset()*60000));
here, is fiddle link : pressme

Javascript get month range by month name

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

Stumped on JS Epoch Convertion

In epoch
1265997351408
is
Fri Feb 12 2010 12:55:51 GMT-0500 (EST)
I am trying to write it as:
February, 12 2010
But I am getting: November, 10 42087
What am I doing wrong?
function makeHumanDate(epoch) {
var theDate = epoch * 1000
var months = new Array(13);
months[0] = "January";
months[1] = "February";
months[2] = "March";
months[3] = "April";
months[4] = "May";
months[5] = "June";
months[6] = "July";
months[7] = "August";
months[8] = "September";
months[9] = "October";
months[10] = "November";
months[11] = "December";
var d = new Date(theDate);
var monthnumber = d.getUTCMonth();
var monthname = months[monthnumber];
var monthday = d.getUTCDate();
var year = d.getFullYear();
if(year < 2000) { year = year + 1900; }
var dateString = monthname +
', ' +
monthday +
' ' +
year;
// Goal is: February, 12 2010
return dateString;
}
I know its something dumb but I've been stuck for a while. Please Help.
Thanks!
You don't need to multiply epoch by 1000 in your example code - if you take this out, it works as expected :)
A little code clean-up
function makeHumanDate(epoch) {
var months = ["January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"],
d = new Date(epoch),
month = months[d.getUTCMonth()],
day = d.getUTCDate(),
year = d.getFullYear();
// not needed as getFullYear returns the full year in 4 digits
//if( year < 2000 ) year += 1900;
return month + ', ' + day + ' ' + year;
}
Your code is fine but your input is broken. If I use http://www.onlineconversion.com/unix_time.htm
I get the same result you do.
Your timestamp seems to need a division by 1000 to get it back into a reasonable frame, after which I get the correct result.

Categories

Resources