DatesHelper.js

import { ONE_DAY } from '../constants/date';

function getMonthTitles(isShort) {
  const monthLong = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
  ];
  const monthShort = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

  return isShort ? monthShort : monthLong;
}

/**
 * Convert timestamp from local timezone to GMT
 * @param  {Date} date Date/Timestamp
 * @return {Number}      Timestamp in GMT
 */
export const getGmtTimestamp = (date) => {
  if (!date) {
    date = new Date();
  }
  // Timestamp in client time zone
  var timestamp = new Date(date).getTime();
  var offset = new Date().getTimezoneOffset(); // in minutes
  // Convert local time to GMT
  timestamp = timestamp + offset * 60 * 1000;
  return timestamp;
};

/**
 * Convert timestamp to local timezone from GMT
 * @param  {Number} timestamp Timestamp
 * @return {Date}   date      Date in current timezone
 */
export const getTimestamp = (timestamp) => {
  var offset = new Date().getTimezoneOffset(); // in minutes
  // Convert to local time from GMT
  return timestamp - offset * 60 * 1000;
};

/**
 * Get time from date as string
 * @param  {Date} date Date object/Timestamp
 * @return {string}      Time as string 'hh:mm:ss am/pm'
 */
export const getTimeStr = (date) => {
  date = new Date(date) || new Date();
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0' + minutes : minutes;
  seconds = seconds < 10 ? '0' + seconds : seconds;
  var strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
  return strTime;
};

/**
 * Get date from date as string
 * @param  {Date} date Date object/Timestamp
 * @return {string}      Date as string 'dd MMM yyyy'
 */
export const getDateStr = (date) => {
  date = new Date(date) || new Date();
  var monthShort = getMonthTitles(true);
  return date.getDate() + ' ' + monthShort[date.getMonth()] + ' ' + date.getFullYear();
};

export const dateAfter = (difference) => {
  return getGmtTimestamp() + difference * ONE_DAY;
};

export function getNumberOfDays(start, end) {
  const date1 = new Date(start);
  const date2 = new Date(end);

  // One day in milliseconds
  const oneDay = 1000 * 60 * 60 * 24;

  // Calculating the time difference between two dates
  const diffInTime = date2.getTime() - date1.getTime();

  // Calculating the no. of days between two dates
  const diffInDays = parseInt(diffInTime / oneDay);

  return diffInDays;
}