Specify date format while parsing date in Javascript - javascript

I want to parse 7Apr2014.
Most of the custom parsing solutions suggest string manipulation using regex or some other hack.
In Java I could simply do this:
new SimpleDateFormat("ddMMMyyyy").parse("07Apr2014")
Is there no way to do this in Javascript?

Not really, there is a Date.parse function but it is implementation dependent and thus unreliable. Your best bet is to manually parse the date or use a date parser library like datejs.
<script language="Javascript" src="date.js" type="text/javascript" />
console.log(Date.parseExact ('07Apr2014', 'ddMMMyyyy'))
Prints:
Date {Mon Apr 07 2014 00:00:00 GMT+0530 (IST)}

function parseDate(s) {
var months = [ "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" ];
var monthStarts;
var yearStarts;
for (var i=1; i<s.length; i++) {
var currentCharIsNumb = !isNaN(parseInt(s[i]));
var previousCharWasNumb = !isNaN(parseInt(s[i -1]));
if (!currentCharIsNumb && previousCharWasNumb)
monthStarts = i;
if (currentCharIsNumb && !previousCharWasNumb)
yearStarts = i;
}
var day = parseInt(s.substring(0, monthStarts));
var monthStr = s.substring(monthStarts, yearStarts);
var month = months.indexOf(monthStr.toLowerCase().substring(0, 3));
var year = parseInt(s.substring(yearStarts));
return new Date(year, month, day);
}

Your date format appears not to be part of the formats supported by Date.parse method.
As you already figured out, it appears we need some custom implementation.
Here is a blog that you might find useful/adopt:
http://lpicquet.wordpress.com/2009/11/03/simpledateformat-in-javascript/

Related

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)

How to get month and year from date in node js

How to get month and year data in Nodejs and query to insert into database?
var months = ["jan", "feb", "mar", "apr", "may", "jun", "july", "aug", "sep", "oct", "nov", "dec"];
var date = new Date();
var month = date.getMonth(); // returns 0 - 11
var year = date.getFullYear();
console.log(months[month]);
console.log(year);
To get the current month and year you can do the following
var date= new Date();
var month = date.getUTCMonth() + 1; //months from 1-12
var year = date.getUTCFullYear();
However i cannot answer on how to save to Database since that depends entirely on the Database and Object Modelling you are using. Can you provide more info on the Database please.
Thanks.

Convert Date to String in format dd-mmm-yyyy [duplicate]

This question already has answers here:
How to subtract days from a plain Date?
(36 answers)
Closed 5 years ago.
I am new to js and I am trying to fiddle with the javascript dates.
I have a following date in the format 01-JAN-2016 and I need to subtract 1 day from it.
I tried
var dateVar = '01-JAN-2016'
var d = new Date(dateVar);
alert(d);
alert(d-1);
It gives me a date and time in long no. But I want it want it to be '31-DEC-2016'
How can I add the format dd-MMM-yyy to it?
You can use datejs library
var dateVar = new Date('01-JAN-2016')
var d = dateVar.add(-1).day().toString('dd-MMM-yyyy');
alert(d);
<script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>
or with plain javascript, you can do like this!
var monthNames = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN",
"JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
];
var date = new Date('01-JAN-2016')
date.setDate(date.getDate() - 1)
date = date.getDate()+"-"+monthNames[date.getMonth()]+"-"+date.getFullYear()
console.log(date)

How do I convert a date entered in a text box into a (dd/mm/yy) format, How do I retrieve the earliest date and latest date?

Eg. Text box requires me to enter a date. If i type in "Sep 1,2016" and "Sep 3,2016" and "Sep 4,2016"
It must be convert and displayed as 1/10/16 - 4/10/16.
How do i do this?
Your question in the title is different from the one in the description.
Converting a string format "Sep 1,2016" to "09/01/16" should be achievable by using:
> "Sep 1,2016".split(/[\s,]+/);
[ 'Sep', '1', '2016' ]
Use an array to determine the month numbers:
var months = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
var monthDigit = months.indexOf("Sep") + 1;
...therefore:
> months.indexOf("Sep") + 1;
9
To add a 0 prior to a single-digit month or day:
var month = "9";
if (month.length === 1) {
month = "0" + month;
}
To get the last two digits of a year, do:
var myYear = "2016";
myYear = myYear.slice(-2);
Once you have your final object, ["09", "01", "16"], all you have to do is use the .join("/"); function to put them in the proper format, the result being "09/01/16"
If you want to order the dates, as asked in the title, you'd have to format the date in a YY/MM/DD format and then sort the strings.
Sorting dates: https://stackoverflow.com/a/30691186/7207316
The Simple Solution
There is no need to convert Strings to Dates or use RegExp.
The simple solution is to use the Array.sort() method. The sort function sets the date format to YYYYMMDD and then compares the string value. Assumes date input is in format DD/MM/YYYY.
data.sort(function(a,b) {
a = a.split('/').reverse().join('');
b = b.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;
});
Run Snippet to Test
<!doctype html>
<html>
<body style="font-family: monospace">
<ol id="stdout"></ol>
<script>
var data = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];
data.sort(function(a,b) {
a = a.split('/').reverse().join('');
b = b.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;
});
for(var i=0; i<data.length; i++)
stdout.innerHTML += '<li>' + data[i];
</script>
</body>
</html>

get all days and dates from month and year using moment.js [duplicate]

This question already has answers here:
How to get list of days in a month with Moment.js
(12 answers)
Closed 3 years ago.
The below code's are getting from moment.js document
moment().date(Number);
moment().date(); // Number
moment().dates(Number);
moment().dates(); // Number
But the input parameter data type is number instead of short month name and year which is mine requirement inputs.
Below is my input format like an array object
`$scope.allMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Act", "Nov", "Dec"];
$scope.Year=2017;// `
So I have month and year, Now I want to get all days and date by using moment.js
Update:
I got the exact result by using normal javascript in my below Answer. But still am unable to find the solution by using moment.js
Parse the date based on the month and year
Loop through the month, formatting each day into an array.
function getMonths(month,year){
var ar = [];
var start = moment(year+"-"+month,"YYYY-MMM");
for(var end = moment(start).add(1,'month'); start.isBefore(end); start.add(1,'day')){
ar.push(start.format('D-ddd'));
}
return ar;
}
console.log(getMonths('Mar',2011))
Finally i got it by javascript
//selected year
$scope.selectedYear = function (value) {
$scope.selectedYearValue = value;// 2011
}
//get days and date from a month and year
$scope.getDaysArray = function (month) {// month count is 2
var names = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var date = new Date($scope.selectedYearValue, month - 1, 1);
$scope.DayAndDate = [];
while (date.getMonth() == month - 1) {
result.push({ "Date": date.getDate(), "Day": names[date.getDay()] });
$scope.DayAndDate.setDate(date.getDate() + 1);
}
}
now the result is
js> getDaysArray(2012)
["1-wed", "2-thu", "3-fri", "4-sat", "5-sun", "6-mon", "7-tue",
"8-wed", "9-thu", "10-fri", "11-sat", "12-sun", "13-mon", "14-tue",
"15-wed", "16-thu", "17-fri", "18-sat", "19-sun", "20-mon", "21-tue",
"22-wed", "23-thu", "24-fri", "25-sat", "26-sun", "27-mon", "28-tue",
"29-wed"]
but i don't want it by using JavaScript instead of moment.js .

Categories

Resources