1

I need to convert json date time to string and write it html table cell. Json I am getting is like this:

 "creation": {
        "date": {
            "year": 2022,
            "month": 1,
            "day": 9
        },
        "time": {
            "hour": 10,
            "minute": 14,
            "second": 11,
            "nano": 830000000
        }

I want to display it like this : 1-9-2022 10:14:11:83000000 Is there built-in function in JS. Your help appreciated

1

2 Answers 2

1

You can create your own function using template literals, check the doc https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

const creation = {
  date: {
      year: 2022,
      month: 1,
      day: 9
  },
  time: {
      hour: 10,
      minute: 14,
      second: 11,
      nano: 830000000
  }
}

const renderTimestanp = ({date, time}) => `${date.month}-${date.day}-${date.year} ${time.hour}:${time.minute}:${time.second}:${time.nano}`

// will return 1-9-2022 10:14:11:83000000
renderTimestanp(creation)

Sign up to request clarification or add additional context in comments.

Comments

0

There is no such build in function, but simple string concatenation will work:

var time = {
  "creation": {
    "date": {
      "year": 2022,
      "month": 1,
      "day": 9
    },
    "time": {
      "hour": 10,
      "minute": 14,
      "second": 11,
      "nano": 830000000
    }
  }
};

console.log(
  '' + time.creation.date.month + '-' + time.creation.date.day + '-' + time.creation.date.year +
  ' ' +
  time.creation.time.hour + ':' + time.creation.time.minute + ':' + time.creation.time.second + ':' + time.creation.time.nano
);

5 Comments

For this case, it's better to use template literals
@Maxime How it's better? Only for readability, but serves same purpose
yes for readability
readability, understanding, learning... if all we do here in StackOverflow is to help, why not do it in the best way possible? 😊 I'm almost sure if you code-review someone that have written your code, you would ask to improve it 👌💪
agree. Maxime solution is reusable and I can call it in places like creation and resolution. Thanks you all

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.