0

The date returned from Json looks like this:

2017-09-14T22:11:05.5303556

I would like it returned in a user friendly format, like:

09/14/2017 22:11:05

This is the Json:

[
{
id: 98,
dateCreated: "2017-09-14T22:11:05.5303556"
},
{
id: 99,
dateCreated: "2017-09-14T22:11:05.5615556"
}
]

And this is the JavaScript:

<script>            
        $.ajax({
            url:'http://mywebsite/api/Response',
            dataType: 'json',               
            success: function(json) {                       
                    myTable = $('#myTable').columns({
                    data:json,
                    schema: [
                        {"header":"ID", "key":"id"},
                        {"header":"Date", "key":"dateCreated"}
                    ],                                                          
                });                     
            }               
        });                     
</script> 

What changes do I have to make to have the date displayed in a user friendly format? Thank you for your help.

bdukes
  • 137,241
  • 21
  • 139
  • 173
romsom
  • 13
  • 3

3 Answers3

1

You might want to check out 10 ways to format time and date using javascript.

You can do something like this, for example, for each of the dates:

var example_date = '2017-09-14T22:11:05.5303556';

function formatDate(date) {
 var d = new Date(date),
  month = d.getMonth(),
  date = d.getDate(),
  year = d.getFullYear(),
  hours = ('0' + d.getHours()).slice(-2),
  minutes = ('0' + d.getMinutes()).slice(-2),
  seconds = ('0' + d.getSeconds()).slice(-2);

    month++;

    return (month + '/' + date +'/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
}

console.log(formatDate(example_date));

You could also make use of .toLocaleTimeString() and .toLocaleDateString() and combine the two.

If you're not averse to using a 3rd party library, I'd recommend taking a gander at MomentJS. It's very good at allowing you to easily format date/time, e.g...

for (var i in json){
  json[i].dateCreated = moment(json[i].dateCreated).format('MM/DD/YYYY hh/mm/ss');
}

...where json is the object returned, would produce:

[{"id":98,"dateCreated":"09/14/2017 10/11/05"},{"id":99,"dateCreated":"09/14/2017 10/11/05"}]
Sam Conran
  • 145
  • 1
  • 7
  • What I don't know is how I have to edit my existing script. – romsom Sep 15 '17 at 18:09
  • Presumably you would need to add the formatting code on the first line of the success function. If you're using moment, copy in that `for` loop I put. Otherwise, define the first function I asted and use the function like so as the first line of the success function: `for (let i in json) { json[i].dateCreated = formatDate(json[i].dateCreated) }` Let me know if that helps? – Sam Conran Sep 15 '17 at 18:34
  • @romsom, awesome :-) Happy to help. Oh, and welcome to Stack Overflow! If you feel this—or any other—answer solved your issue, please consider marking it as accepted by [clicking the check mark](https://i.stack.imgur.com/QpogP.png). This helps keep the focus on older SO which still don't have answers. – Sam Conran Sep 15 '17 at 19:49
1

I think the new Date(date).toLocaleDateString() would get the job done

Example:

   $.ajax({
        url: 'http://mywebsite/api/Response',
        dataType: 'json',               
        success: function(json) {
           const data = json.map((obj) => (
              Object.assign(
                 {},
                 obj,
                 { dateCreated: new Date(obj.dateCreated).toLocaleDateString() }
              )
           ));

           myTable = $('#my-table').columns({
              data: data,
              schema: [
                 { "header": "ID", "key": "id" },
                 { "header": "Date", "key": "dateCreated" }
              ],                                                          
           });               
        }               
    });

I hope that helps ^__^

bigfanjs
  • 577
  • 5
  • 16
  • What I don't know is where I have to add the new lines in the script. – romsom Sep 15 '17 at 18:08
  • When I'm adding those lines I'm getting an error in the console and nothing is displayed on the page: ---> VM238:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () at Object.success (00.htm:26) at j (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at x (jquery.min.js:4) at XMLHttpRequest.b (jquery.min.js:4 – romsom Sep 16 '17 at 04:04
  • Again please see my updated response. It has to work now because I tested it. For simple use case like this you don't have to load a large library like momentJS. – bigfanjs Sep 16 '17 at 11:14
  • I might have missed something but now I get the following error: index2.htm:24 Uncaught TypeError: $(...).columns is not a function at Object.success (index2.htm:24) at fire (jquery-1.12.4.js:3232) at Object.fireWith [as resolveWith] (jquery-1.12.4.js:3362) at done (jquery-1.12.4.js:9840) at XMLHttpRequest.callback (jquery-1.12.4.js:10311) – romsom Sep 18 '17 at 16:36
0

Date formatting in JavaScript has been done a million times over.

If you just want a simple format, see this SO answer. If you want something more robust, I would recommend Moment.js.

Moment example: moment().format('MMMM Do YYYY, h:mm:ss a');

Produces: September 15th 2017, 12:57:45 pm

Strikegently
  • 1,738
  • 14
  • 19