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?

3 Answers 3

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');
Sign up to request clarification or add additional context in comments.

1 Comment

Since the question is for CURRENT_TIMESTAMP, this should be marked as the correct answer
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.

1 Comment

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.)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.