SNIPPETS - JAVASCRIPT

  1. Home
  2. Docs
  3. SNIPPETS – JAVASCRIPT
  4. DATES

DATES

Getting previous “Monday”

function getPreviousMonday( date ) {
    date = date || new Date();
    if ( typeof date == 'string')
	date = new Date( date );

    var day = date.getDay();
    var prevMonday = new Date();
    if (day == 0 || day == 1){
        prevMonday.setDate(date.getDate() - (day + 6));
    } else{
        prevMonday.setDate(date.getDate() - (day - 1));
    }

    return prevMonday;
}

target any day

let target = 1 // Monday
let date = new Date()
date.setDate(date.getDate() - ( date.getDay() == target ? 7 : (date.getDay() + (7 - target)) % 7 ))

Get next day of week

function nextDate( date, dayIndex ) {
    dayIndex = dayIndex || 0   // Sunday
    date = date || new Date();

    if ( typeof date == 'string')
        date = new Date( date );

    date.setDate(
	date.getDate() +
	(dayIndex - 1 - date.getDay() + 7) % 7
	+ 1);
	 
    return date;
}

Get next day

var tomorrow = new Date();
tomorrow.setDate( tomorrow.getDate() + 1 );

DATE to ISO

var todayDate = new Date().toISOString().slice(0, 10);

with timezone correction:

function isoDate( date, slice ){
	slice = slice || true;
	// timezone offset in milliseconds
	let tzoffset =
		(new Date()).getTimezoneOffset() * 60000,
		
	result =
		(new Date(date - _CAL.tzoffset)).toISOString()
	if ( slice ) result = result.slice(0, 10)
	
	return result;
}

toLocaleDateString() options

let date = new Date();

let options = {
    weekday: "short",
    year: "numeric",
    month: "2-digit",
    day: "numeric"
};

let str = date.toLocaleDateString("el-GR", options)
);
Option          Values          Sample output
----------------------------------------------------
weekday         'narrow'        'M'
                'short'         'Mon'
                'long'          'Monday'

year            '2-digit'       '01'
                'numeric'       '2001'

month           '2-digit'       '01'
                'numeric'       '1'
                'narrow'        'J'
                'short'         'Jan'
                'long'          'January'

day             '2-digit'       '01'
                'numeric'       '1'

hour            '2-digit'       '12 AM'
                'numeric'       '12 AM'

minute          '2-digit'       '0'
                'numeric'       '0'

second          '2-digit'       '0'
                'numeric'       '0'

timeZoneName    'short'         '1/1/2001 GMT+00:00'
                'long'          '1/1/2001 GMT+00:00'

Get First and Last Day of the Current Month

const now = new Date();

const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
console.log(firstDay); // 👉️ Sat Oct 01 2022 ...

const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
console.log(lastDay); // 👉️ Mon Oct 31 2022 ...