7

Just trying to do some simple messaging here:

   var post = {
        sender_username : sender_username,
        recipient_username : recipient_username, 
        message_no : 1,
        content : content, 
        time : ***CURRENT TIMESTAMP***, 
        read : 0
    };

    connection.query('INSERT INTO message SET ?', post, function(err, result) {
        if (err) {
            res.send(err);
        }
        else {
            res.send(post); 
        }
    });

What's the simplest way to stick the date and time in there that is valid for the TIMESTAMP type?

senjougahara
  • 287
  • 1
  • 4
  • 13

3 Answers3

24

You can use Moment.js for this purpose:

Date.now returns current timestamp in millisecond and moment also works with milliseconds.

var mysqlTimestamp = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
Salar
  • 5,305
  • 7
  • 50
  • 78
4

The native JS way can be found in the answers here.

Personally, I use Moment.js for anything that deals with dates.

moment().utc().format('hh:mm:ss')

NOTE: I got confused with your question. You asked for "CURRENT_TIME" but your format is TIMESTAMP. MySQL's TIME and TIMESTAMP types are different. TIMESTAMP contains both the date and time and the default value function for that is "CURRENT_TIMESTAMP". I'm assuming you're referring to the TIME type.

Community
  • 1
  • 1
hyubs
  • 737
  • 6
  • 18
  • I happened to already be using moment for birthdays, so this is awesome. Node.js has some great modules! (EDIT: I actually meant the TIMESTAMP type. I'll clear that up in my post.) – senjougahara Jun 01 '14 at 08:20
0

You can use {time: new Date(GMTtimeString).toLocaleString()} where GMTtimeString sent from front-end.

Itzhak Galitch
  • 366
  • 4
  • 19