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)
Related
Well, I want to print out the name of the month from the .getMonth() method.
Keeping in mind that the array index starts from 0, I've made this code:
let date = new Date();
let month = date.getMonth();
month -= 1;
// As array index start from 0 but month from 1, I'm subtracting 1 from it so it too will start from 0.
let months =
[
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
Now I want like if it's May, I will keep the value 4, then subtract 1, which is 3.
The 3rd index in the array months is "May", but how will I ask it to check for the element with its index number?
NOTE : Please don't suggest if statements, because I don't want to use if statements for just displaying elements.
Easy: use the bracket property accessor notation:
let date = new Date
let month = date.getMonth()
let months =
[
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
console.log(months[month])
Arrays are little more than objects with properties named after the positive integers (ie. '0', '1', '2' etc). Because JavaScript is weakly typed you can supply a number (eg. from getMonth!) to the bracket property accessor notation, and the value will be coerced to a string, giving you the result you want.
But, as Jaromanda X points out, the better way is to use the Intl API because this will guarantee accuracy for a given user locale:
const date = new Date
console.log(new Intl.DateTimeFormat('en', { month: 'short'}).format(date))
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.
I am trying to fill blank values when no data available for particular months. Here is plunker.. http://plnkr.co/edit/f0IklkUfX8tkRZrn2enx?p=preview
$scope.year = [
{"month":"mar", "val":"23"},
{"month":"feb", "val":"45"},
{"month":"jan", "val":"56"}
];
var total = ["jan", "feb", "mar", "apr", "may", "jun", "aug", "sep", "oct", "nov", "dec"];
for(var i=0; i<total.length; i++){
if($scope.year[i].month === undefined){ //logic here to see absent month.
$scope.year.push(
{
"month":total[i],
"val":"0"
})
}
}
I have created array of default total months items for compare each month item from expected object, if the item is absent in expected object, need to create empty item or with value "0" in expected object itself.
You can do something like following
Js Update
var year = [
{"month":"mar", "val":"23"},
{"month":"feb", "val":"45"},
{"month":"jan", "val":"56"}
];
var total = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
// Current months array
var currentMonth = [];
angular.forEach(year, function(item){
currentMonth.push(item.month);
});
// iterating over months
for(var i=0; i<total.length; i++){
//$scope.year = [];
// checking if month is absent
if(currentMonth.indexOf(total[i]) === -1){ //logic here to see absent month.
year.push(
{
"month":total[i],
"val":"0",
"order" : i
})
} else {
year[currentMonth.indexOf(total[i])].order = i; // adding order
}
}
$scope.year = year;
Markup
<!-- Order by new property order -->
<td ng-repeat="item in year | orderBy: 'order'">
{{item.val}}
</td>
For reference - http://plnkr.co/edit/km6jLQv8wxm1XP8QCxvV?p=preview
year[i] is undefined, so you try get field of object that don't exist.
try it "if($scope.year[i] === undefined)"
Your idea of using orderBy won't work based on month because you aren't looking for an alphabetical sort.
Following creates array of months that exist in the data. Then it loops over all months in year and adds missing data. Finally sort the data based on months indexing
// create array of months available in data
var availableMonths = $scope.year.map(function(item){
return item.month;
});
// loop over all months and if it doesn't exist in data add it
total.forEach(function(mo){
if(availableMonths.indexOf(mo) ===-1 ){
$scope.year.push({"month":mo, "val":"0" })
}
});
// sort data using index of months
$scope.year.sort(function(a,b){
return total.indexOf(a.month) > total.indexOf(b.month);
});
remove the orderBy filter in html since data is already sorted
Steps 2 & 3 above could actually be combined to splice() the array so final order is correct but for ease of understanding I left them as separate operations
DEMO
Try this.
$scope.year = [
{"month":"jan", "val":"56"},
{"month":"feb", "val":"45"},
{"month":"mar", "val":"23"}
];
var total = ["jan", "feb", "mar", "apr", "may", "jun", "aug", "sep", "oct", "nov", "dec"];
for(var i=0; i<total.length; i++){
if(!$scope.year[i] || $scope.year[i].month === undefined){
$scope.year.push(
{
"month":total[i],
"val":"0"
})
}
}
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 .
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/