esd100
esd100

Reputation: 529

In javascript, how do I extract the month from date string "yyyy-mm-dd" or timeStamp?

I have a database with certain logged events as json objects, each one with it's own JS millisecond timestamp and also a date string in the format "yyyy-mm-dd", as well as a minutes entry.

I'd like to use either the timestamp or the date string, whichever is easier, as input into an algorithm which will count how many logs were entered in a given month.

I would also like the algorithm to sum the cumulative number of minutes were logged in a given month.

For example,

log1: {
Date:"2017-05-24",
TimeStamp:1495612800,
Minutes: 15},
log2: {
Date:"2017-05-19",
TimeStamp:1495180800,
Minutes: 45},
log3: {
Date:"2017-04-24",
TimeStamp:1493020800,
Minutes:30}

In this example, the algorithm would count that there are two logs in the month of May and one log in the month of April.

The algorithm would also return a sum of 60 minutes in the month of May and 30 minutes in the month of April.

Any help with parsing the input into the appropriate variables for counting would be greatly appreciated!

Thanks

Upvotes: 2

Views: 4657

Answers (6)

Fanky
Fanky

Reputation: 1795

To get month as mm from yyyy-mm-dd you can simply:

log1.Date.substring(5, 7);

to get it as integer (without leading zeros):

parseInt(log1.Date.substring(5, 7));

Upvotes: 0

mhodges
mhodges

Reputation: 11126

To get the month from a single object it would be as simple as the following:

var month = new Date(log1.TimeStamp * 1000).getMonth() +1 getMonth() is zero-based, so you need to add 1

To count the number of occurrences per month, you can do this:

var logs = [{
    Date: "2017-05-24",
    TimeStamp: 1495612800,
    Minutes: 15
  },
  {
    Date: "2017-05-19",
    TimeStamp: 1495180800,
    Minutes: 45
  },
  {
    Date: "2017-04-24",
    TimeStamp: 1493020800,
    Minutes: 30
  }
];

var occurrences = logs.reduce(function (result, current) {
  // multiply unix timestamp by 1000 to get ms
  var date = new Date(current.TimeStamp * 1000);
  var month = date.getMonth() + 1;
  if (!result[month]) {
    result[month] = {
      occurrences: 0,
      minutes: 0
    };
  }
  result[month].occurrences++;
  result[month].minutes += Number(current.Minutes);
  return result;
}, {});

console.log(occurrences);

If you wanted to group the dates by year and then by month, it would require just a slight change to the code. It would look like the following:

var logs = [{
    Date: "2017-05-24",
    TimeStamp: 1495612800,
    Minutes: 15
  },
  {
    Date: "2017-05-19",
    TimeStamp: 1495180800,
    Minutes: 45
  },
  {
    Date: "2017-04-24",
    TimeStamp: 1493020800,
    Minutes: 30
  }
];

var occurrences = logs.reduce(function(result, current) {
  // multiply unix timestamp by 1000 to get ms
  var date = new Date(current.TimeStamp * 1000);
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  // make sure result[year] is defined
  if (!result[year]) { 
    result[year] = {};
  }
  // notice the original code below is now [year][month]
  if (!result[year][month]) {
    result[year][month] = {
      occurrences: 0,
      minutes: 0
    };
  }
  result[year][month].occurrences++;
  result[year][month].minutes += Number(current.Minutes);
  return result;
}, {});

console.log(occurrences);

Upvotes: 2

RobG
RobG

Reputation: 147513

Given that the month number is already available in the Date property, there's no need to use a Date object:

var logs = [
  {Date: "2017-05-24", TimeStamp: 1495612800, Minutes: 15},
  {Date: "2017-05-19", TimeStamp: 1495180800, Minutes: 45},
  { Date: "2017-04-24", TimeStamp: 1493020800, Minutes: 30}
];

var logMonthCount = logs.reduce(function(acc, log) {
  var month = log.Date.split('-')[1];
  acc[month] = acc[month]? acc[month]+1 : 1;
  return acc;
}, Object.create(null));

console.log(logMonthCount);

If using the TimeStamp property, it will be treated as UTC and converted to the local date based on the client timezone. So it may well be that for some logs within the timezone offset of the host from the start or end of the month, that the month in the Date property is a different month to that returned by new Date(log.timeStamp*1000).getMonth()) + 1.

Upvotes: 1

Dalin Huang
Dalin Huang

Reputation: 11342

JavaScript getMonth() Method

The getMonth() method returns the month (from 0 to 11) for the specified date, according to local time.

Note: January is 0, February is 1, and so on.

Use a function (note: you need convert UNIX timestamp to milliseconds so just time 1000 inside getMon function):

UNIX timestamps are in seconds

function getMon(timestamp) {
  return (new Date(timestamp * 1000)).getMonth() + 1;
}

var log1 = {Date: "2017-05-24",TimeStamp: 1495612800};
var log2 = {Date: "2017-05-19",TimeStamp: 1495180800};
var log3 = {Date: "2017-04-24",TimeStamp: 1493020800};

function getMon(timestamp) {
  return (new Date(timestamp * 1000)).getMonth() + 1;
}

console.log(getMon(log1['TimeStamp']));
console.log(getMon(log2['TimeStamp']));
console.log(getMon(log3['TimeStamp']));

Upvotes: 2

Dai
Dai

Reputation: 155648

Using the Date(miliseconds) constructor will be the most robust approach, just in case the date format were to change.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

new Date(value);

value Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC, with leap seconds ignored (Unix Epoch; but consider that most Unix time stamp functions count in seconds).

var log1 = { Date: "2017-05-24", TimeStamp: 1495612800 };
var log1Date = new Date( log1.TimeStamp * 1000 );
log1Date.toLocaleString(); // "5/24/2017"

The *1000 is because the TimeStamp value provided looks to be in seconds, but JavaScript requires a milisecond value.

Upvotes: 1

Oliver
Oliver

Reputation: 173

Using your timestamps, this should work:

var date = new Date(1495612800 * 1000);
var month = date.getMonth();

Then just implement a count against the result

Upvotes: 0

Related Questions