Search code examples
javascriptcodepen

Time formatting from UTC with Moment.js


How do I convert a utc time to this format using moment.js

"YYYY Do MM hh:mm:ss"

I am trying to follow and use this method which is in the "Parse a date" portion of the following tutorial: https://flaviocopes.com/momentjs/

moment(dt).format("YYYY Do MM hh:mm:ss");

But it just makes the date disappear.

Codepen: https://codepen.io/centem/pen/ExYEoLj

var options = {
  valueNames: ['date', 'number']
};
var ResultDiv = new List('ResultDiv', options);
ul {
  list-style-type: none;
  padding-left: 0;
  margin-left: 0;
}

span {
  margin-right: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>


<div id="ResultDiv">
  <input class="search" placeholder="Search" />
  <button class="sort" data-sort="date">
    Sort by Date
  </button>
  <button class="sort" data-sort="number">
    Sort by Number
  </button>
  <button>Last 7 Days</button>
  <button>Last 30 Days</button>

  <ul class="list" id="ul">
    <li>
      <span class="2019-01">
          <script>
            let dt = new Date("2019-04-15T15:10:45Z");
            document.write(dt);
            //2019-04-15T15:10:45Z;
            //moment(dt).format("YYYY Do MM hh:mm:ss");
          </script>
            </span>
      <span class="number">76</span>
    </li>
    <li>
      <span class="date">2019-02-12T11:21:10Z</span>
      <span class="number">23</span>
    </li>
    <li>
      <span class="date">2019-01-12T10:20:16Z</span>
      <span class="number">14</span>
    </li>
    <li>
      <span class="date">2019-01-09T09:20:16Z</span>
      <span class="number">7</span>
    </li>
    <li>
      <span class="date">2019-07-11T11:01:05Z</span>
      <span class="number">101</span>
    </li>
    <li>
      <span class="date">2019-08-29T11:01:05Z</span>
      <span class="number">121</span>
    </li>
    <li>
      <span class="date">2019-09-11T11:01:05Z</span>
      <span class="number">130</span>
    </li>
  </ul>

</div>

Solution:

 let current_datetime = new Date("2019-04-15T15:10:45Z")
        let formatted_date = current_datetime.getFullYear() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getDate() + " " + current_datetime.getHours() + ":" + current_datetime.getMinutes() + ":" + current_datetime.getSeconds() 
        console.log(formatted_date)

        let dt = new Date("2019-04-15T15:10:45Z");
        document.write(formatted_date);

Solution

  • Your issue is that momentjs isn't loaded when your <script> tag is called. CodePen loads JavaScript after the DOM has loaded. You need to move your code into the JavaScript portion of your CodePen. I recommend adding the date to your node and querying for those nodes, updating the node's content via innerText. I've updated your pen: https://codepen.io/kkirby/pen/zYOWJxX