How to use date-fns - 10 common examples

To help you get started, we’ve selected a few date-fns examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github fosslife / delta / tests / testCron.js View on Github external
});
        await apendFile('testUploads/' + filename, lor);
        const execString = `touch -a -m -t ${randomDate} testUploads/${filename}`;

        execCommands.push(execString);
    }

    // execute the modification command
    for (const i of execCommands) {
        await exec(i);
    }

    const files = await readDirAsync(uploadsPath());
    for (const file of files) {
        const fileStats = getFileStats(file);
        const diff = differenceInDays(new Date(), fileStats.date);
        if (diff > fileStats.retention) {
            await deleteAsync(uploadsPath(fileStats.file));
            console.log(
                `Deleting ${fileStats.file} as ${diff} > ${
                    fileStats.retention
                } created at ${format(fileStats.date, 'DD MMM YYYY')} Size: ${
                    fileStats.size
                }`
            );
        }
    }

    // Delete generated test files
    // fs.rmdirSync("testUploads");   => node can't delete folder that's not empty?
    exec('rm -rf testUploads/');
}
github hasadna / open-bus / firebase / client / src / components / RideViewer / RideViewer.js View on Github external
const handleClick = () => {console.log('click on point')}
  const { _lat, _long } = point.point;
  return (
    
  );
}
github upvalue / meditations / frontend / src / habits / ScopeDays.tsx View on Github external
export const ScopeDays = (props: ScopeDaysProps) => {
  const { tasks, date } = props;

  const days = groupBy(tasks, t => formatDate(parseDate(t.date.split(' ')[0])));

  const start = startOfMonth(date);
  let end = endOfMonth(date);

  const now = new Date();

  if (end > now) {
    end = now;
  }

  if (end > start) {
    // Ensure that days before the current day are given a scope, even with no tasks
    eachDayOfInterval({ start, end }).forEach(day => {
      const key = formatDate(day);

      if (!days[key]) days[key] = [];
    });
  }
github nusmodifications / nusmods / packages / nusmoderator / src / academicCalendar.ts View on Github external
export function getAcadYearStartDate(acadYear: string): Date {
  const shortYear = acadYear.split('/')[0];
  const targetYear = 2000 + parseInt(shortYear, 10);
  const firstDateOfMonth = new Date(targetYear, 7, 1, 0, 0, 0);
  const nearestMonday = startOfWeek(firstDateOfMonth, { weekStartsOn: 1 });

  if (isBefore(nearestMonday, firstDateOfMonth)) {
    const firstMonday = addWeeks(nearestMonday, 1);
    return firstMonday;
  }
  // 1st Aug is already a Monday
  return nearestMonday;
}
github hashicorp / vault / ui / app / helpers / parse-date-string.js View on Github external
export function parseDateString(date, separator = '-') {
  // Expects format MM-yyyy by default: no dates
  let datePieces = date.split(separator);
  if (datePieces.length === 2) {
    if (datePieces[0] < 1 || datePieces[0] > 12) {
      throw new Error('Not a valid month value');
    }
    let firstOfMonth = new Date(datePieces[1], datePieces[0] - 1, 1);
    if (isValid(firstOfMonth)) {
      return firstOfMonth;
    }
  }
  // what to return if not valid?
  throw new Error(`Please use format MM${separator}yyyy`);
}
github MacKentoch / react-redux-graphql-apollo-bootstrap-webpack-starter / src / front / redux / modules / userAuth.js View on Github external
export function setUserLogout(time: string = format(new Date(), dateFormat)) {
  auth.clearAllAppStorage();
  return {
    type: SET_USER_LOGOUT,
    time,
    isAuthenticated: false,
    user: emptyUser,
  };
}
// //////////////////////////////
github cornerstonejs / react-cornerstone-viewport / src / helpers / formatDA.js View on Github external
export default function formatDA(date, strFormat = 'MMM d, yyyy') {
  if (!date) {
    return;
  }

  // Goal: 'Apr 5, 1999'
  try {
    const parsedDateTime = parse(date, 'yyyyMMdd', new Date());
    const formattedDateTime = format(parsedDateTime, strFormat);

    return formattedDateTime;
  } catch (err) {
    // swallow?
  }

  return;
}
github upvalue / meditations / frontend / src / habits / HabitsContainerState.ts View on Github external
const scopeMounted = (currentDate: string, date: string): ScopeMountedResult => {
  const currentDateObj = parse(currentDate, 'yyyy-MM', baseDate);
  // If year
  const yearCheck = parse(date, 'yyyy', baseDate);
  const monthCheck = parse(date, 'yyyy-MM', baseDate);
  const dayCheck = parse(date, 'yyyy-MM-dd', baseDate);
  if (isValid(yearCheck)) {
    return format(currentDateObj, 'yyyy') === date && 'Year';
  } else if (isValid(dayCheck)) {
    return currentDate === format(dayCheck, 'yyyy-MM') && 'Days';
  } else if (isValid(monthCheck)) {
    // Must come after days check
    return format(currentDateObj, 'yyyy-MM') === date && 'Month';
  }
  return false;
}
github gpbl / react-day-picker / package / lib / index.js View on Github external
function getWeeks(month, props) {
    var locale = props.locale, fixedWeeks = props.fixedWeeks;
    var monthStart = dateFns.startOfMonth(month);
    var monthEnd = dateFns.endOfMonth(month);
    var diff = dateFns.differenceInDays(monthEnd, monthStart);
    var weeks = {};
    var lastWeekStr = '';
    for (var i = 0; i <= diff; i++) {
        var date = dateFns.addDays(monthStart, i);
        var dateWithModifiers = new DateWithModifiers(date, {}, props);
        var week = dateFns.getWeek(dateWithModifiers.date, { locale: locale });
        if (week === 1 && dateFns.getMonth(date) === 11) {
            week = 53;
        }
        var weekStr = week.toString();
        if (!weeks[weekStr]) {
            var startDays = getOutsideStartDays(dateWithModifiers, props);
            // Create a new week by adding outside start days
            weeks[weekStr] = startDays;
        }
        weeks[weekStr].push(dateWithModifiers);
        lastWeekStr = weekStr;
    }
    var lastWeek = weeks[lastWeekStr];
    var lastDay = lastWeek[lastWeek.length - 1];
github Adphorus / react-date-range / src / components / DateRange.js View on Github external
const { ranges, onChange, maxDate, moveRangeOnFirstSelection } = this.props;
    const focusedRangeIndex = focusedRange[0];
    const selectedRange = ranges[focusedRangeIndex];
    if (!selectedRange || !onChange) return {};

    let { startDate, endDate } = selectedRange;
    if (!endDate) endDate = new Date(startDate);
    let nextFocusRange;
    if (!isSingleValue) {
      startDate = value.startDate;
      endDate = value.endDate;
    } else if (focusedRange[1] === 0) {
      // startDate selection
      const dayOffset = differenceInCalendarDays(endDate, startDate);
      startDate = value;
      endDate = moveRangeOnFirstSelection ? addDays(value, dayOffset) : value;
      if (maxDate) endDate = min([endDate, maxDate]);
      nextFocusRange = [focusedRange[0], 1];
    } else {
      endDate = value;
    }
    // reverse dates if startDate before endDate
    if (isBefore(endDate, startDate)) {
      [startDate, endDate] = [endDate, startDate];
    }

    if (!nextFocusRange) {
      const nextFocusRangeIndex = findNextRangeIndex(this.props.ranges, focusedRange[0]);
      nextFocusRange = [nextFocusRangeIndex, 0];
    }
    return {
      range: { startDate, endDate },