Pergunta

Javascript Time Frame


I'm trying to write a Node app that grabs data entries from MySQL based on a time frame equal to the beginning and end of the current work week.


Here's the Node-MySQL query:

function retrieveSales(){

    connection.query('select * from sales_entries where date BETWEEN ? AND ?',
    timeFrame,

    function (err, rows, fields) {

        var sales = new Array();

        for (x=0;x<rows.length;x++){
            sales.push(rows[x]);
        }

        return sales;

    });
}

where timeFrame is an array of two dates in datetime format, which is the second-specific time data-type that MySQL offers as a default. ( 31/12/2010 03:55 AM )


The problem is, I've never worked much with dates in JS. So I have two questions:

  1. Would it be better to record a different date format to the database, or is datetime fine?

  2. How should I generate this array with values equal to the beginning of the first day of the current work week (monday) and end of the last day of the current work week (friday) respectively?


The Fiddle

Here's the JSFiddle, including three functions; retrieveSales, which performs the query, dateTime(), returning the current time in datetime format, and retrieveData which is the main function that will call all necessary queries.

Foi útil?

Solução

In general, I would say use the ISO8601 format in your database and everywhere else and http://momentjs.com/docs/ to deal with al your dates.

Still, you can work with a date time string like you have, just parse into 'a moment' using a custom format string.

// parse from string, see docs for format
var t = moment('31/12/2010 03:55 AM', "DD/MM/YYYY hh:mm A"); 

// ISO-8601
t.format()

// and back to that MySQL format
t.format("DD/MM/YYYY hh:mm A");

You can do a lot of computerations on t (comparisons, mutations, formatting), just check the momentjs docs.

Edit: more specifically, filling timeFrame could be as follows:

// from sun to saterday of this week
var timeFrame = [ moment().days(0).format("DD/MM/YYYY hh:mm A")
                , moment().days(6).format("DD/MM/YYYY hh:mm A") ];

// or since method.days() wraps around, this is monday-sunday
var timeFrame = [ moment().days(1).format("DD/MM/YYYY hh:mm A")
                , moment().days(7).format("DD/MM/YYYY hh:mm A") ];

HTH

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top