最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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

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

Share Improve this question edited May 26, 2017 at 22:47 esd100 asked May 26, 2017 at 22:15 esd100esd100 5291 gold badge7 silver badges14 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 2

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);

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']));

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

https://developer.mozilla/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.

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.

Using your timestamps, this should work:

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

Then just implement a count against the result

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));

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论