Skip to content

Instantly share code, notes, and snippets.

@skvggor
Last active May 4, 2018 17:13
Show Gist options
  • Save skvggor/5f7f83c15efc1499d645e7dc8394ebfa to your computer and use it in GitHub Desktop.
Save skvggor/5f7f83c15efc1499d645e7dc8394ebfa to your computer and use it in GitHub Desktop.
Get yesterday - format: yyyy-mm-dd
function yesterday() {
'use strict';
var date = new Date();
function formatNumberTo2Digits(number) {
return ('0' + (number)).slice(-2);
}
// magic
date.setDate(date.getDate() - 1);
var year = date.getFullYear();
var month = formatNumberTo2Digits(date.getUTCMonth() + 1);
var day = formatNumberTo2Digits(date.getUTCDate());
return year + '-' + month + '-' + day;
}
function yesterday(timestamp) {
'use strict'
const date = new Date(timestamp)
date.setDate(date.getDate() - 1)
const formatNumberTo2Digits = (number) => ('0' + (number)).slice(-2)
const year = date.getFullYear()
const month = formatNumberTo2Digits(date.getUTCMonth() + 1)
const day = formatNumberTo2Digits(date.getUTCDate())
return year + '-' + month + '-' + day
}
// Uses:
yesterday(new Date()) // '2018-05-03'
yesterday('2018-05-04T17:07:54.467Z') // '2018-05-03'
yesterday('Tue 01-01-2009 6:00') // '2008-12-31'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment