-1

how can I get date in this format in JS? I tried using .toISOString() but I don't quite get the result that I need.

2022-12-22 11:35:23 -0400

Thanks

MrRobot
  • 1,001
  • 1
  • 14
  • 34

3 Answers3

0

I don't know any fast way, but you can use something like this: To get a date in the format "YYYY-MM-DD HH:mm:ss ZZ" in JavaScript, you can use the following code:

const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1; // months are zero-indexed, so we need to add 1
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const timeZoneOffset = date.getTimezoneOffset();
const timeZoneOffsetHours = Math.floor(Math.abs(timeZoneOffset) / 60);
const timeZoneOffsetMinutes = Math.abs(timeZoneOffset) % 60;
const timeZoneOffsetString = (timeZoneOffset < 0 ? '+' : '-') +
    (timeZoneOffsetHours < 10 ? '0' : '') + timeZoneOffsetHours +
    ':' + (timeZoneOffsetMinutes < 10 ? '0' : '') + timeZoneOffsetMinutes;

const formattedDate = `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day} ${hours}:${minutes}:${seconds} ${timeZoneOffsetString}`;

This will give you a string like "2022-12-22 11:35:23 -0400".

Kalomano
  • 41
  • 1
0

This is tricky to do with vanilla JavaScript, however it's simple to do using a library such as luxon.

We create a new DateTime object, date, then call DateTime.toFormat() to present the date in the desired format.

const { DateTime } = luxon;

const date = DateTime.now();
console.log('Formatted date:', date.toFormat('yyyy-MM-dd HH:mm:ss ZZZ'))
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js" integrity="sha512-6ZJuab/UnRq1muTChgrVxJhSgygmL2GMLVmSJN7pcBEqJ1dWPbqN9CiZ6U3HrcApTIJsLnMgXYBYgtVkJ8fWiw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
-1

What format do you want? Did you use Date? Here is very useful library I use a lot. Date FNS there is format function and you can set format you want. Function returns string

boki_bo
  • 80
  • 9