0

I want to filter data by current month (maybe additionally add next month data). I don't know how to go from the beginning.
In theory I think I could compare current month and month date from my data and then to display data only if two months variables match.
I thought I should start like this:

var myDate = new Date();
var thisMonth = new Date(myDate);
thisMonth.setMonth(myDate.getMonth()+1);
var nextMonth = new Date(myDate);
nextMonth.setMonth(myDate.getMonth()+2);

Thank you in advance for any kind of help!

Additional detailed explanation:
I copied SharePoint 2013 list whose data I displayed on SharePoint site page.
In content editor web part I wrote javascript code to show that list as a table.
I have two date columns (from/until) but they are displayed in table as YYYY-MM-DD HH:MM:SS. Looks to me like ISO date format. I saw several examples how to convert in js that type of date into date type like DD.MM.YYYY. None worked for me or I didn't know how to do it correctly. So I created calculated field that will present date type as text/string, after this I managed to show date on js table the way I wanted.

Danilo
  • 223
  • 1
  • 4
  • 19

3 Answers3

2

You should not parse strings with the Date constructor (or Date.parse, they are equivalent for parsing) as it's largely implementation dependent and notoriously unreliable.

I have two date columns (from/until) but they are displayed in table as YYYY-MM-DD HH:MM:SS. Looks to me like ISO date format.

Almost. The extended format is YYYY-MM-SSTHH:MM:SS, the T can be replaced by a space on agreement between parties exchanging the date but it's not strictly correct. If the timezone is omitted, it's treated as a "local" date (i.e. the host timezone offset is used in calculating the moment in time that it represents).

According to ECMA-262, if the format is not correct, browsers can either:

  1. Treat it as invalid ISO 8601 and return an invalid date
  2. Treat it as not ISO 8601 and fall back to whatever parsing algorithm they wish to use

So given:

new Date('2017-01-01 23:12:12')

Firefox returns a Date for 1 Jan 2017 23:12:12 in the host time zone, Safari returns an invalid date. Both are consistent with the standard.

So if you need a Date object, you should parse the string manually using either a library (e.g. fecha.js or moment.js) or a simple function.

But anyway, you don't need to parse the strings to a Date to reformat the string, just use string methods and avoid Date parsing vagaries completely.

function filterCurrentMonth() {
  // Create string for comparison
  var d = new Date();
  var currentMonth = d.getFullYear() + '-' + ('0' + (d.getMonth()+1)).slice(-2);
  // Hide rows that don't have string in the first cell
  var rows = document.getElementById('t0').rows;
  [].forEach.call(rows, function(row) {
    if (row.cells[0].textContent.indexOf(currentMonth) == -1) {
      row.style.display = 'none';
    } else {
      row.style.display = '';
    }
  });
}

function filterNone() {
  var rows = document.getElementById('t0').rows;
  [].forEach.call(rows, function(row) {
      row.style.display = '';
  });
}
#t0 {
  font-size: 60%;
}
<button onclick="filterCurrentMonth()">Show only current month rows</button>
<button onclick="filterNone()">Show all rows</button>
<table id="t0">
  <tr><td>2017-01-01 23:12:12<tr><td>2017-02-01 23:12:12<tr><td>2017-05-01 23:12:12
  <tr><td>2017-03-01 23:12:12<tr><td>2017-04-01 23:12:12<tr><td>2017-12-01 23:12:12
  <tr><td>2017-10-01 23:12:12<tr><td>2017-11-01 23:12:12<tr><td>2017-06-01 23:12:12
  <tr><td>2017-07-01 23:12:12<tr><td>2017-09-01 23:12:12<tr><td>2017-08-01 23:12:12
  <tr><td>2017-01-01 23:12:12<tr><td>2017-02-01 23:12:12<tr><td>2017-05-01 23:12:12
  <tr><td>2017-03-01 23:12:12<tr><td>2017-04-01 23:12:12<tr><td>2017-12-01 23:12:12
  <tr><td>2017-10-01 23:12:12<tr><td>2017-11-01 23:12:12<tr><td>2017-06-01 23:12:12
  <tr><td>2017-07-01 23:12:12<tr><td>

<!-- begin snippet: js hide: false console: true babel: false -->

23:12:122017-08-01 23:12:12

Similarly, if you want to reformat the string to be DD.MM.YYYY you can just reformat the string:

/* Format string in YYYY-MM-DD HH:mm:ss format to DD.MM.YYYY
** @param {string} s - string in YYYY-MM-DD HH:mm:ss format
** @returns {string} in DD.MM.YYYY format
*/
function formatYMDtoDMY(s) {
  var b = s.split(/\D/);
  return b[2] + '.' + b[1] + '.' + b[0];
}

console.log(formatYMDtoDMY('2017-10-01 23:12:12'))

Note however that dates should use unambiguous formats like DD-MMM-YYYY, e.g. 01-Jan-2017. It only takes one more line of code for that. ;-)

RobG
  • 142,382
  • 31
  • 172
  • 209
1

Are you asking?

I don't know how to go from the beginning.

You could get the beginning from current month and the last date of next month by following code:

<html>
<script>
  var myDate = new Date();
  var thisMonth = new Date(myDate.getFullYear(), myDate.getMonth(), 1);
  var nextMonth = new Date(myDate.getFullYear(), myDate.getMonth() + 2, 0);
  
  console.log("Date start: " + thisMonth);
  console.log("Date end: " + nextMonth);
  console.log("Formatted date start: " + formatDate(thisMonth));
  console.log("Formatted date end: " + formatDate(nextMonth));

  function padLeft(n){
    return ("00" + n).slice(-2);
  }

  function formatDate(){        
    var d = new Date,
        dformat = [ d.getFullYear(),
                    padLeft(d.getMonth()+1),
                    padLeft(d.getDate())
                    ].join('-')+
                    ' ' +
                  [  padLeft(d.getHours()),
                     padLeft(d.getMinutes()),
                     padLeft(d.getSeconds())].join(':');
     return dformat
  }

</script>
</html>

I hope it helps you. Bye.

Alessandro
  • 4,382
  • 8
  • 36
  • 70
1

Don't forget, getMonth() returns a Number, from 0 to 11, representing the month, and Date make the date as object with methods and properties

There is a lot of examples here

var date         = new Date('2010-10-11 00:00:00');
var formatDate   = date.getDate() + '/' 
                 + (date.getMonth() + 1) + '/' 
                 +  date.getFullYear();

console.log( formatDate );

So you can always pass the date on any format but there some important moments you can read here:

Converting string to date in js

Community
  • 1
  • 1
Daniel
  • 611
  • 5
  • 20
  • 1
    `new Date('2010-10-11 00:00:00')` produces an invalid date in Safari so this function returns "NaN/NaN/NaN". There's no need to parse the string to a Date. – RobG Jan 27 '17 at 22:33
  • As RobG wrote, this script worked only in firefox. In IE it showed NaN instead of date. Anyway, Thanks Daniel for your effort and time! – Danilo Jan 30 '17 at 14:26