1

I am getting json from backend like this :

 {
   "datas":[
      {
         "id":4,
         "create_date":"2021-03-18T21:11:57.239Z"
      },
      {
         "id":5,
         "create_date":"2021-03-19T19:37:05.829Z"
      }
   ]
}

and looping through json like below :

 $(data.datas).each(function(index,value){
        html += `<tr><th scope="row">${index+1}</th>
              <td>${value.id}</td>
              <td>${value.create_date}</td>
              <td><a href="#" class="btn btn-outline-dark">View Car</a></td>
            </tr>`
 })

But, here create_date is just printing in td column like this 2021-03-18T21:11:57.239Z . So, how can i make this display like this 2021-03-18 & 21:11 am/pm in each tds ?

My attempt :

var created_date = value.create_date;
console.log(created_date.split("T")[0]);//2021-03-18
console.log(created_date.split("T")[1])//21:11:57.239Z (how can i remove 57.239Z..)

I am open for both solution i.e : backend as well as frontend . For my backend i am using django let me know if you need to see any code from backend .

Swati
  • 28,069
  • 4
  • 21
  • 41

2 Answers2

1

For solving it from backend side. You can set it in settings.py

REST_FRAMEWORK = {
    'DATETIME_FORMAT': "%Y-%m-%d & %H:%M %p",
}

More information in DRF Documentation

The output will looks like it:

"create_date": "2021-03-18 & 21:11 AM"

Mamed
  • 95
  • 4
  • 16
1

You can apply MomentJS to format the date time in front-end.

Pre-requisites:

  • Add the MomentJS script into your HTML

// Demo with assign sample data into createdDate
var created_date = new Date();
console.log(moment(created_date).format("YYYY-MM-DD & HH:mm a"));
// Result: 2021-04-02 & 15:16 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Reference: MomentJS Parse string format

Yong Shun
  • 35,286
  • 4
  • 24
  • 46