1

I have a date format problem. my json is pulling a date that looks like 2021-08-04T06:00:00.000Z I am not sure how to convert it to a 08-04-2021 format. Anyone able to provide some insight? I have provided the js I used to fetch the data from google sheets. here is the script in google sheets Ultimately I must be confused on where to put the datetimeformater info.

    var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();

        return ContentService
        .createTextOutput(JSON.stringify(response))
        .setMimeType(ContentService.MimeType.JSON);

}

var try_num = 5
var delayInMilliseconds = 500;
function getVarFromUrl(url) { return url.match(/[?](.*)/)[1]; }

function fetch_data(url) {
    fetch(url)
    .then(response => {
        if (response.ok) {
            return response.json()
        } else if(response.status === 404) {
            return Promise.reject('error 404')
        } else {
            return Promise.reject('some other error: ' + response.status)
        }
    })
    .then(data => main(data))
    .catch(error => start());
}

function start() {
    setTimeout(function() {
        if (try_num >= 1) {
            try_num -= 1
            fetch_data('https://script.google.com/macros/s/AKfycbztu69qk4fkFqVqSHLC2hIxuN9xiHFJgsYr-nMvhGQungJN0S6r/exec')
        }
    }, delayInMilliseconds)
}

function main(data) {
    console.log(data)
    var rows = data[0].data
    console.log(rows)
    for (var row_num in rows) {
        document.getElementById("table").innerHTML += "<tr id='" + row_num + "'></tr>"
        console.log(rows[row_num])
        for (var element_num in rows[row_num]) {
            console.log(rows[row_num][element_num])
            document.getElementById(row_num).innerHTML += "<th>" + rows[row_num][element_num] + "</th>" 
        }
    }
}

window.onload = function() {
    start()
}
Jürgen Fink
  • 3,162
  • 2
  • 23
  • 25
J2 K
  • 19
  • 2
  • 1
    Does this answer your question? [How do I get the current date in JavaScript?](https://stackoverflow.com/questions/1531093/how-do-i-get-the-current-date-in-javascript) – ponury-kostek Sep 02 '21 at 16:25
  • I guess I am just not sure how to add the code for datetimeformater – J2 K Sep 02 '21 at 16:32

3 Answers3

1

First you have to get the Date instance like this:

const date = new Date(date_string | '2021-08-04T06:00:00.000Z')

Then you can format it like shown in this question.


In your case you should do:

new Intl.DateTimeFormat('en').format(date).replace(/\//g, '-')
javalsai
  • 33
  • 8
  • 1
    There are more options of date formatting here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat – javalsai Sep 02 '21 at 16:56
  • Goog answer, there is a small typo, though at the logical **OR** ( || ) operator: ` | ` should be ` || ` – Jürgen Fink Sep 02 '21 at 19:15
  • Result: **8-4-2021** (single digits); if you apply more options as mentioned by @javalsai like `new Intl.DateTimeFormat('en-US', { day:'2-digit', month: '2-digit', year: 'numeric'})`, then result would be: **08-04-2021** which is the requested format of initial question. Anyhow, good answer. – Jürgen Fink Sep 02 '21 at 19:52
0

var d = new Date('2021-08-04T06:00:00.000Z');
console.log(d.getUTCHours()); // Hours
console.log(d.getUTCMinutes());
console.log(d.getUTCSeconds());
  • Please add further details to expand on your answer, such as working code or documentation citations – cursorrux Sep 02 '21 at 17:45
  • 1
    Please add further details to expand on your answer, such as working code or documentation citations. – Community Sep 02 '21 at 17:45
  • Actually, you are extracting the **UTC time** of the ISO date, not the required **date string**. Approach would be: `d.getDate(); d.getMonth() + 1; d.getFullYear());` Note that month is zero-based, hence you have to add +1 – Jürgen Fink Sep 02 '21 at 18:34
0

Adding to the good answers presented:

As you just need the date string of the ISO date, one approach would be:

  1. getting those first 10 characters
  2. splitting them into their 3 parts (year / month / day)
  3. concat parts according to your needs
function formatDate(date) {
  if(date) {
    // get first 10 characters of ISO date
    // split into 3 parts
    parts = date.substring(0, 10).split('-');

    if (parts.length == 3) {
      // concat parts: (month: parts[1], day: parts[2],  year: parts[0])
      dateFormatCustom = parts[1] + '-' + parts[2] + '-' + parts[0];
    } else {
      dateFormatCustom = '';
    };
    return dateFormatCustom;
  } else {
    return '';
  };
};

Then implement above funtion whithin your for (var element_num in rows[row_num]) { ... loop:

for (var element_num in rows[row_num]) {
  // ...

  // your dates are at index 7 and 8 of each row
  if (element_num == 7 || element_num == 8) {
    rows[row_num][element_num] = formatDate(rows[row_num][element_num]);
  };

  // ...
};

Following complete code to Run code snippet:

var try_num = 5
var delayInMilliseconds = 500;

// declared url as variable meanwhile for testing here:
const url = 'https://script.google.com/macros/s/AKfycbztu69qk4fkFqVqSHLC2hIxuN9xiHFJgsYr-nMvhGQungJN0S6r/exec';

function getVarFromUrl(url) { return url.match(/[?](.*)/)[1]; }

function fetch_data(url) {
    fetch(url)
    .then(response => {
        if (response.ok) {
            return response.json()
        } else if(response.status === 404) {
            return Promise.reject('error 404')
        } else {
            return Promise.reject('some other error: ' + response.status)
        }
    })
    .then(data => main(data))
    .catch(error => start());
}

function start() {
    setTimeout(function() {
        if (try_num >= 1) {
            try_num -= 1
            // fetch_data('https://script.google.com/macros/s/AKfycbztu69qk4fkFqVqSHLC2hIxuN9xiHFJgsYr-nMvhGQungJN0S6r/exec')
            fetch_data(url);
        }
    }, delayInMilliseconds)
}

// declared additional variables outside function:
let parts, dateFormatCustom;

// added this function to convert ISO date to your custom format:
function formatDate(date) {
  if(date) {
    // split into parts the date-string of ISO date (first 10 characters)
    parts = date.substring(0, 10).split('-');

    if (parts.length == 3) {
      // concat parts: (month: parts[1], day: parts[2],  year: parts[0])
      dateFormatCustom = parts[1] + '-' + parts[2] + '-' + parts[0];
    } else {
      dateFormatCustom = '';
    };
    return dateFormatCustom;
  } else {
    return '';
  };
};

function main(data) {
    // console.log(data);
    var rows = data[0].data;
    //console.log(rows);

    for (var row_num in rows) {
        document.getElementById("table").innerHTML += "<tr id='" + row_num + "'></tr>"
        console.log(rows[row_num])
        for (var element_num in rows[row_num]) {

          // apply the new function to convert to your desired date format

          // your dates are at index 7 and 8 of each row
          if (element_num == 7 || element_num == 8) {
            rows[row_num][element_num] = formatDate(rows[row_num][element_num]);
          };
          console.log(rows[row_num][element_num]);
          document.getElementById(row_num).innerHTML += "<th>" + rows[row_num][element_num] + "</th>"
        };
    }
}

window.onload = function() {
    start()
}
<table id="table"></table>

Note:
You could use alternatively following methods, but they return single digits for values < 10:

getDate();  // day
getMonth() + 1; // Zero based index, hence you have to add +1
getFullYear();  // don't confuse with 'getYear()' that is no longer recommended

To overcome the single digits results, you could apply:

  1. toString() method, to convert result into a string
  2. padStart() method, to 'fill' with an extra '0' where needed
    MDN String.padStart()

Hence, we would have the following:

let yourDate = new Date('2021-08-04T06:00:00.000Z');
document.write(yourDate);

let dd, mm, yyyy;
dd = yourDate.getDate().toString().padStart(2, '0');
mm = (yourDate.getMonth() + 1).toString().padStart(2, '0');
yyyy = yourDate.getFullYear().toString().padStart(2, '0');

document.write('<br><br>');
document.write('Month: ' + mm);

document.write('<br>');
document.write('Day: ' + dd);

document.write('<br>');
document.write('Year: ' + yyyy);

document.write('<br><br>');
document.write('US: ' + mm +'-' + dd + '-' + yyyy);
Jürgen Fink
  • 3,162
  • 2
  • 23
  • 25