TimeStamp Project--not returning unix timestamp correctly

TimeStamp Project--not returning unix timestamp correctly
0

#1

As I am almost done with the project from FCC (https://www.freecodecamp.com/challenges/timestamp-microservice)

I am not able to figure out why when the input is in standard time, it won’t output its Unix timestamp correctly.

For instance, when I type:

http://localhost:3000/January%201%201970
it will output as so:

{“unix”:“28800”,“natural”:“January 1, 1970”}
It seems like there is an offset of 8 hours (28800 seconds, but even when I apply the utcOffset(), it doesn’t change.

Here is my code so far:

var express = require('express');
var path = require('path')
var app = express();
var moment = require('moment')
var port = 3000;
//homepage
app.get('/', function(req, res) {
  var fileName = path.join(__dirname, 'index.html');
  res.sendFile(fileName, function (err) {
    if (err) {console.error(err)}
    console.log('This is the homepage')
  });
});

//input of the page
app.get('/:dataString', function(req, res) {
  var dataString = req.params.dataString;
  var output;
  //Using regex, checks if the dataString has only number characters
  if(/^[0-9]*$/.test(dataString)){
    output = moment(dataString, "X")
  } else{
    console.log(dataString)
    output = moment(dataString, "MMMM DD YYYY")
    console.log(output.utc().format("X"))
  }

  if (output.isValid()){
    res.json({
      unix: output.utc().format("X"),
      natural: output.utc().format("MMMM D, YYYY")
    });
  } else{
    res.json({
      unix: 'null',
      natural: 'null'
    });
  }
})

app.listen(port,function(){
  console.log("turn on. Port is: ", port)
})

#2

I realize that you must have long since moved past this, but since I had the same problem, I’m going to put the solution here as a reference:

You need to use utc mode when creating the moment, rather than offsetting it afterwards:

output = moment.utc(dataString)

This creates the moment in the utc timezone rather than your local time, which is the behavior you’re looking for.


#3

Thanks man! It’s good to know this stuff!