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]);
Related
I have a date 24/05/2021, I want to convert its date format to 24/May/2021 using Javascript or jquery as user leaves textbox, my client don't want to use date picker, he just want to type dates straight and auto convert date as he leaves the textbox, like he does in excel.
I find many ways but got nothing, I know how to do it server side but it has to be done at client side.
As you said that client don't want to use date picker, you need to define the format that user will input.
You can split every segment and then format the month, then put the value in the input element's value on DOM.
As for the example below, I assume that the user uses / as the separator for the input.
function formatDate(val){
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var parts = val.split('/');
var d = parts[0];
var y = parts[2];
var m = months[parseInt(parts[1], 10) - 1];
var inp = document.querySelector('#inp');
if(/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/.test(val)){
inp.value = `${d}/${m}/${y}`;
} else inp.value = "";
}
<input type="text" id="inp" required pattern="[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}" onchange="formatDate(this.value)"/>
you can use regex to check if the date inputted is correct or not, if it is correct then you can change its format, otherwise you can show error. Here is the code:
const month = ["January","February","March","April","May","une","July","August","September","October","November","December"];
const dateregex = /^[0-3]?[0-9]\/[0-1]?[0-9]\/[0-9][0-9][0-9][0-9]/
class DateField {
constructor(id) {
this.elem = document.getElementById(id);
this.elemInp = this.elem.children[1];
this.elemError = this.elem.children[0];
this.date = null;
this.elemInp.addEventListener('blur', () => {
console.log(dateregex.test(this.elemInp.value), dateregex, this.elemInp.value);
if (!dateregex.test(this.elemInp.value)) {
this.showError();
this.date = null;
return;
}
var datesplits = this.elemInp.value.split('/');
this.date = new Date();
this.date.setYear(parseInt(datesplits[2],10));
this.date.setDate(parseInt(datesplits[0],10));
this.date.setMonth(parseInt(datesplits[1],10) - 1);
var newDateString = this.date.getDate() + '/' + month[this.date.getMonth()] + '/' + this.date.getFullYear();
this.elemInp.value = newDateString;
this.removeError();
});
this.elemInp.addEventListener('focus', () => {
if (this.date !== null && !isNaN(this.date.getTime())) {
var newDateString = this.date.getDate() + '/' + (this.date.getMonth() + 1) + '/' + this.date.getFullYear();
this.elemInp.value = newDateString;
}
});
}
showError() {
this.elemError.innerText = "date is invalid";
}
removeError() {
this.elemError.innerText = "";
}
}
var d1 = new DateField("dateContainer");
<html>
<head>
<title>try js</title>
</head>
<body>
<div id="dateContainer">
<p style="color: red;"></p>
<input type="text" id="date" />
</div>
</body>
</html>
You can split the string on "/" and then with the second array element you make an array with the months like this:
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
Then you split your string on "/" and get a date like:
const split = document.querySelector("#input").split("/");
const date = new Date(`${split[1]}/${split[0]}/${split[2]}`);
And finally:
const month = monthNames[date.getMonth()];
The HTML is gonna be something like this:
<input type="text" id="input" required onchange="formatDate(this.value)"/>
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>
This question already has answers here:
Get month name from Date
(40 answers)
Closed 5 years ago.
Here is my Code:
var listDate = [];
var startDate ='2017-02-01';
var endDate = '2017-02-10';
var dateMove = new Date(startDate);
var strDate = startDate;
while (strDate < endDate){
var strDate = dateMove.toISOString().slice(0,10);
listDate.push(strDate);
dateMove.setDate(dateMove.getDate()+1);
};
console.log(listDate);
//["2017-02-01", "2017-02-02", "2017-02-03", "2017-02-04", "2017-02-05", "2017-02-06", "2017-02-07", "2017-02-08", "2017-02-09", "2017-02-10"]
it gives me the output with the month number like 2017-02-01, but i need the month name instead of month number. Pleae Help.
try this simple way :
Create an array with all the month name's, and so use your index as key to find the good month.
var monthNames = ["January", "February", "March", "April", "May","June","July", "August", "September", "October", "November","December"];
var d = new Date();
console.log("The current month is " + monthNames[d.getMonth()]);
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 });
});
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);
});