2

I have a requirement of generating dates in this format 'Thru: 12/20' (like credit/debit card expiry date format). What is the best way of generating date in this format?

new Date().toJSON().slice(0,7).split('-').reverse().join('/')

I got the date in mm/yyyy format but couldn't get the desired result

Manu J
  • 133
  • 9

2 Answers2

4

You can use Intl.DateTimeFormat to generate date in day name and dd/MM format

const options = { weekday: 'short', month: 'numeric', day: 'numeric' };
const result = new Intl.DateTimeFormat('en-GB', options).format(new Date());
console.log(result);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

With Moment you can simply do:

const date = moment().format("ddd DD/MM");
console.log("Valid until : " + date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • Thanks. Is there any way to do this using Js only ? – Manu J Dec 12 '21 at 16:22
  • 2
    Let's avoid recommending external libs in 2020+ when the browsers provide `Intl.DateTimeFormat` – anthumchris Dec 12 '21 at 16:33
  • 1
    As with any other JS written by other people, Moment is still JS … but I wouldn't recommend using it today: https://momentjs.com/docs/#/-project-status/ – Quentin Dec 12 '21 at 16:33
  • I've tried Luxon, I don't like it. It's harder to use than Moment and takes much of the easy syntax away. I think I'll keep using good ol'Moment as long as it works. Or as @AnthumChris said, just use `Intl.DateTimeFormat`. – Jeremy Thille Dec 12 '21 at 16:38