Improving the appearance of dates and times in JSON replies using JavaScript

Upon clicking a link, my JavaScript triggers an AJAX call to retrieve JSON data, which is then used to populate a modal.

The link triggering the JavaScript code is as follows:

<?= $this->Html->link(__('View'), ['action' => 'popup', $session->id], ['class' => 'view', 'data-id' => $session->id]) ?>

This action is part of a table within a CakePHP 3 View. The value for $session->id is based on the clicked row of data. The 'popup' action is a simple function in CakePHP 3 that enables the functionality of the JavaScript and opening the modal.

The JavaScript code responsible for triggering the modal is provided below:

<script type="text/javascript">
    $(function () {
        $('.view').click(function (ev) {
            ev.preventDefault();
            var sessionId = $(this).attr('data-id');
            $('#viewModal').modal('show');
            $.ajax({
                url:"localhost/project/sessions/details/"+sessionId+".json",
                type:'POST',
                success:function(res) {
                    if(res) {
                        document.getElementById("prdatestart").innerHTML = res.date_start;
                        document.getElementById("prstarttime").innerHTML = res.starttime;
                    }
                }
            });
        });
    });
</script>

The 'details' function in my CakePHP 3 SessionsController retrieves the necessary data for the obtained $session->id:

public function details($id = null)
    {
        $details = $this->Sessions->get($id);
        $this->set(array(
            'output' => $details,
            '_serialize' => 'output',
            '_jsonp' => true
        ));
    }

This is the structure of my modal that opens:

<!-- Modal -->
<div class="modal fade" id="viewModal" tabindex="-1" role="dialog" aria-labelledby="viewModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h3 class="modal-title" id="viewModalLabel">Session Details</h3>
                <br>
                <table class="vertical table col-sm-2">
                    <tr>
                        <th>Starting Date:</th>
                        <td id="prdatestart"></td>
                    </tr>
                    <tr">
                        <th>Starting Time:</th>
                        <td id="prstarttime"></td>
                    </tr>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close
                </button>
            </div>
        </div>
    </div>
</div>

However, the dates and times are in the following format:

  • Date: 2017-05-12T00:00:00+00:00
  • Time: 2017-03-31T00:14:00+11:00

For the date response, I require only the date in D/M/Y format. For the time response, I need only the time in 12-hour hh:mm AM/PM format. (The timezone information at the end was considered when initially submitting the data).

Answer №1

Utilizing basic JavaScript, you can simply use new Date() in a function called cal(yourdatevarible ,whichtype) where type=date|time.

var date = '2017-05-12T00:00:00+00:00';
var time = '2017-03-31T00:14:00+11:00';

console.log(cal(date, 'date'))
console.log(cal(time, 'time'))

function cal(date, type) {

  var months = ['Jan', 'Feb', 'Mar', 'Aprl', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  //var weekends =['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  var currentDate = new Date(date)
  var hours = currentDate.getHours() > 12 ? currentDate.getHours() - 12 : currentDate.getHours();
  var format = currentDate.getHours() > 12 ? 'PM' : 'AM';
  if (type == 'date') {
    return currentDate.getDate() + ' ' + months[currentDate.getMonth()] + ' ' + currentDate.getFullYear();
  } else {
    var minutes = currentDate.getMinutes().toString().length > 1 ? currentDate.getMinutes() : '0' + currentDate.getMinutes();
     hours = hours.toString().length > 1 ? hours : '0' + hours;
    return hours + ':' + minutes + ' ' + format;
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process of adding information to a JSON file?

I'm looking to store my data in an external JSON file and have it update the list when the page is reloaded. Can anyone assist with this? Below is my code: $scope.addUser = function() { var user = { id: null, login: '', ...

Converting Vuetify data-table computed properties to SQL query transformation

I have a straightforward attendance application that is currently storing data in a SQL database. However, I am faced with the task of storing a computed property in the SQL database as well. Here is a snippet of the configuration: ...

Repeated trigger of click events on dynamically created divs

When making an Ajax call, I dynamically generate a div and create a click action associated with it. I give the div a unique ID based on a key value from the data. The problem arises when the same key value is received in subsequent Ajax calls. var $order ...

detecting user interactions with hyperlinks

Can links be intercepted in an Angular application to block specific URLs like YouTube links without adding custom attributes or elements? Is it possible to intercept all clicks on links within the scope of a particular controller's view without modi ...

Executing API calls utilizing Axios in a NodeJS environment with the Authorization Basic feature

I have developed an API to retrieve a token from PayPal. curl -v POST https://api.sandbox.paypal.com/v1/oauth2/token \ -H "Accept: application/json" \ -H "Accept-Language: en_US" \ -u "CLIENT_ID:SECRET" &b ...

Generating a new object from a TypeScript class using JavaScript

Currently, I am facing an issue while attempting to call a JavaScript class from TypeScript as the compiler (VS) seems to be having some trouble. The particular class in question is InfoBox, but unfortunately, I have not been able to locate a TypeScript d ...

Guide to creating JSDoc for a TouchEvent handler

Looking to improve my shorter-js codebase with JSDoc for TypeScript definitions, but hitting a roadblock. I've implemented the on() function using Element.addEventListener, working well so far. However, when passing a TouchEvent as a parameter for an ...

Utilize JavaScript or JQuery to create a dynamic pop-up window that appears seamlessly on the

Looking to create a unique feature on an HTML page? Want a clickable link that opens a "pop-up" displaying a specific image, right within the page rather than in a new tab or window? Ideally, this pop-up should be movable around the page like a separate ...

What causes the issue of divs not stacking properly when using Bootstrap 4?

I'm currently working on integrating VueJs and bootstrap4 to create two basic components. However, I am facing an issue where I have assigned the class .col-md-4 to a div in order to add 3 elements per row, but only one element is being added per row ...

I'm puzzled, can anyone provide clarification on the concept of xml?

Recently, Sheshank S. provided me with a solution to my question, but I failed to grasp its meaning. Can someone please explain it to me? Despite looking through various tutorials on websites and videos, none of them have been able to clarify what this cod ...

Can you help me understand how to extract data from a JSON string in iPhone using Objective-C?

After successfully parsing a JSON string on my iPhone, I encountered an error: -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x62242e0 2011-08-16 16:11:58.792 BleepBleep[4083:207] *** Terminating app due to uncaught exception 'N ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

Resetting the index and length in Vue.js each time a new page is loaded

Currently facing an unusual issue that I'm struggling to resolve. My goal was to include an index number in a for-each loop and calculate the total count of data within my vue.js component. While I successfully achieved this, I encountered a problem w ...

Passing a deconstructed object as a parameter for a function

I'm having trouble understanding the parameter const Posts in the code snippet below. As a newcomer to node/React, I'm not sure if it's a destructured parameter object or just an object being passed as a parameter. The functions getPosts an ...

SQL query for retrieving an email address embedded in a string

Could you assist me in creating a SQL query to extract the email address from a text field that contains a json object like the following? {"objectType":"Agent","mbox":"mailto:<a href="/cdn-cgi/l/email-protection" clas ...

What is the best way to transfer information from an old JSON file to a new JSON file using JavaScript

I have a JSON file and I need to extract the content of "data" where the provider is "AXIS DATA" into a new JSON file. How can this be achieved? Here's what I've attempted: First, I convert it using JSON.parse and then search for the desired da ...

Utilizing the HTML button element within an ASP file combined with JavaScript can lead to the reloading of the

I am attempting to create a JavaScript function for an HTML button element. However, I have noticed that it causes the page to reload. Strangely, when I use an input with a button type, everything works perfectly. What could be causing this issue and why a ...

What is the best way to activate ui-sref in an AngularJS unit test?

Currently I am conducting a test on an AngularJS view. The code sample contains some non-standard helpers, but they should not affect the specific functionality being tested. Below is the view (written in Jade): #authentication-options button#sign-up(u ...

Sending an HTTP post request with form data and various field controls will not be directed to a Java backend

Recently, I've started working with AngularJs and I'm facing an issue with uploading image files along with their labels through a Jax-RS post rest API. My problem is that the control in my AngularJS controller is not entering the Java post API. ...

Why are two vertical scrolls appearing on the screen simultaneously?

I utilized this method to hide the body scrollbar initially and then display it upon clicking a link: $('body').css('overflow', 'hidden'); $('#site').click(function(e) { $('#wrapper').remove(); $(& ...