How to use the parse function from date-fns

Find comprehensive JavaScript date-fns.parse code examples handpicked from public code repositorys.

date-fns.parse is a JavaScript library function that converts a date string or timestamp into a JavaScript Date object.

227
228
229
230
231
232
233
234
235
        }
    })
}

//parse date and time for computation
const timeInParse = parse(checkIfTimeInExist.timeIn, timeFormat, new Date());
const timeOutParse = parse(timeOut, timeFormat, new Date());
const startShiftParse = parse(findCrew.startShift, timeFormat, new Date());
const endShiftParse = parse(findCrew.endShift, timeFormat, new Date());
fork icon0
star icon3
watch icon1

+ 275 other calls in file

187
188
189
190
191
192
193
194
195
196
}

const {email , password , startShift, endShift, dailyRate, firstName, lastName} = req.body

const endShiftParse = parse(endShift, timeFormat, new Date());
const startShiftParse = parse(startShift,timeFormat, new Date());

let hourlyRate =  dailyRate /  (((endShiftParse.getTime() - startShiftParse.getTime())/3600000) - 1);

const checkEmailIfExists = await User.findOne({email:email})
fork icon0
star icon3
watch icon1

+ 87 other calls in file

How does date-fns.parse work?

date-fns.parse works by taking a date string or timestamp as its input and returning a JavaScript Date object representing that date and time. The function first checks the format of the input string to determine which parsing strategy to use. If the format is recognized, date-fns.parse uses a set of parsing rules to extract the date and time information from the input string and creates a new Date object with the corresponding values. If the format is not recognized or the input is a timestamp, date-fns.parse assumes that the input represents a Unix timestamp, which is the number of milliseconds since January 1, 1970, and creates a new Date object with the corresponding timestamp. Once the Date object is created, date-fns.parse returns it as the result of the function. Note that date-fns.parse is part of the date-fns library, which provides a set of utility functions for working with dates and times in JavaScript, and supports various date formats and locales.

923
924
925
926
927
928
929
930
931
932
933
934
935
};


// date functions


const getTodayObj = () => new Date();
const getDateObj = (dateString) => parse(dateString, 'yyyy-MM-dd', new Date());
const formatDate = (dateObj) => format(dateObj, 'yyyy-MM-dd');


const isAFutureDate = (dateString) => {
  const date = getDateObj(dateString);
fork icon0
star icon2
watch icon0

+ 35 other calls in file

834
835
836
837
838
839
840
841
842
843
844
845
  const specialDate = special.release_date;
  return isToday(specialDate);
};


const getToday = () => new Date();
const parseDate = (dateString) => parse(dateString, 'yyyy-MM-dd', new Date());


const isAFutureDate = (dateString) => {
  const date = parseDate(dateString);
  return isBefore(getToday(), date);
fork icon0
star icon2
watch icon1

+ 11 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
const { parse } = require("date-fns");

const dateString = "2022-03-31T10:30:00.000Z";
const timestamp = 1648757400000;

const dateFromString = parse(dateString);
const dateFromTimestamp = parse(timestamp);

console.log(dateFromString);
console.log(dateFromTimestamp);

In this example, we first import the parse function from the date-fns library and define a date string and a Unix timestamp. We then use parse to create two new Date objects, one from the date string and one from the timestamp. The resulting dateFromString and dateFromTimestamp objects are JavaScript Date objects representing the same date and time, and can be used for various date and time operations. Note that date-fns.parse can also be used with various date formats and time zones, and can return different parts of the Date object, such as the year, month, day, hour, minute, second, and millisecond.

257
258
259
260
261
262
263
264
265
266
267
268
app.post("/todos/", async (req, res) => {
  const { id, todo, priority, status, category, dueDate } = req.body;


  addNewTodo = async () => {
    try {
      const parseDate = await parse(dueDate, "yyyy-MM-dd", new Date());
      const resultDate = await format(parseDate, "yyyy-MM-dd");


      let addTodoQuery = `
            INSERT INTO
fork icon0
star icon1
watch icon1

+ 5 other calls in file

12
13
14
15
16
17
18
19
20
21

const options = { locale: fr }
const formatDate = formatWithOptions(options)

const numberOfDaysInLate = date => differenceInCalendarDays(date)(new Date())
const parseDate = date => parse(date, 'dd/MM/yyyy', new Date())
const formatDateWithLittleEndianLongFormat = ifElse(isNil, () => '', formatDate('dd/MM/yyyy'))
const formatDateWithInternationalLongDateTimeFormat = formatDate('yyyy-MM-dd:HH:mm:ss')
const earliestDate = (firstDate, secondDate) => (isAfter(firstDate)(secondDate) ? firstDate : secondDate)
const latestDate = (firstDate, secondDate) => (isBefore(firstDate)(secondDate) ? firstDate : secondDate)
fork icon1
star icon0
watch icon0

141
142
143
144
145
146
147
148
149
150
  return dateFns.max.apply(null, dates)
}
exports.minImpl = function(dates) {
  return dateFns.min.apply(null, dates)
}
exports.parseImpl = dateFns.parse
exports.setDateImpl = dateFns.setDate
exports.setDayImpl = dateFns.setDay
exports.setDayOfYearImpl = dateFns.setDayOfYear
exports.setHoursImpl = dateFns.setHours
fork icon0
star icon2
watch icon1

+ 16 other calls in file

158
159
160
161
162
163
164
165
166
167
    if (!data[0]) throw new Error('Failed to receive school year');
    return {
        name: data[0].name,
        id: data[0].id,
        startDate: parse(data[0].startDate, 'yyyyMMdd', new Date()),
        endDate: parse(data[0].endDate, 'yyyyMMdd', new Date())
    };
}

/**
fork icon16
star icon0
watch icon0

+ 7 other calls in file

122
123
124
125
126
127
128
129
130
131

formatDate: (value, format = longDateFormat) => {
  if (!value) {
    return value
  }
  const parsedDate = dateFns.parse(value)

  if (!dateFns.isValid(parsedDate)) { return value }
  return dateFns.format(parsedDate, format)
},
fork icon8
star icon0
watch icon1

+ 3 other calls in file

8
9
10
11
12
13
14
15
16
17


//PARSE
// const dataNasc = '20/01/1981';

// const resultado = parse(dataNasc, "dd/MM/yyyy", new Date());

// console.log(resultado);

//ADD
fork icon0
star icon0
watch icon1

712
713
714
715
716
717
718
719
720
721
].includes(code);
if (closeButton) {
    inputRef.value.blur();
}
if (props.typeable) {
    const parsedDate = dateFns.parse(inputRef.value.value, props.inputFormat, new Date(), { locale: props.locale });
    if (dateFns.isValid(parsedDate)) {
        input.value = inputRef.value.value;
        emit('update:modelValue', parsedDate);
    }
fork icon0
star icon0
watch icon0

+ 19 other calls in file

13
14
15
16
17
18
19
20
21
22
23
24
const dataRegistroDeposito = format(new Date(), "yyyy-dd-MM kk:mm:ss");
console.log("deposito:", dataRegistroDeposito);


//Método parse
//Converte string em objeto js
const parseDate = parse('02/11/2014', 'MM/dd/yyyy', new Date());
console.log("parse:", parseDate);


//Método add
//Faz operações aritiméticas (somar/subtrair) de um objeto de data. Ele não modifica o objeto original, cria um novo.
fork icon0
star icon0
watch icon0

165
166
167
168
169
170
171
172
173
174
  .sort("-createdAt")
  .limit(1);

if (rewards.length > 0) {
  const lastRewardTimeString = rewards[0].time_granted;
  const lastRewardTime = parse(
    lastRewardTimeString,
    "dd MM yyyy HH:mm",
    new Date()
  );
fork icon0
star icon0
watch icon1

+ 59 other calls in file

133
134
135
136
137
138
139
140
141
142
if (dateFns.isDate(value)) return value;
try {
  const date = dateFns.parseISO(value);
  if (dateFns.isValid(date)) return date;

  const milliUnixDate = dateFns.parse(value, 'T', new Date());
  if (dateFns.isValid(milliUnixDate)) return milliUnixDate;

  throw new InvalidDateTimeError(`Invalid format, expected a timestamp or an ISO date`);
} catch (error) {
fork icon0
star icon0
watch icon1

+ 46 other calls in file

139
140
141
142
143
144
145
146
147
148
149
150
  const day = String(today.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}


const calculateDifferenceInDays = (dateStr1, dateStr2) => {
  const date1 = parse(dateStr1, 'yyyy-MM-dd', new Date());
  const date2 = parse(dateStr2, 'yyyy-MM-dd', new Date());


  const numDays = differenceInDays(date2, date1);

fork icon0
star icon0
watch icon1

+ 129 other calls in file

111
112
113
114
115
116
117
118
119
120
121


//Invalid Due Date
const checkDueDate = async (request, response, next) => {
  const { date } = request.query;
  try {
    const parsedDate = parse(date, "yyyy-MM-dd", new Date());
    const result = format(parsedDate, "yyyy-MM-dd");
    queryBox.dueDate = result;
    next();
  } catch (error) {
fork icon0
star icon0
watch icon1

+ 29 other calls in file

4
5
6
7
8
9
10
11
12
13
14
module.exports = function (stringValue, formatString, localeString) {
  const cleanFormatString = standardiseFormatString(formatString);
  let dateValue;


  if (cleanFormatString) {
    dateValue = parse(
      stringValue,
      cleanFormatString,
      new Date(),
      localeString ? { locale: locale[localeString.replace("-", "")] } : undefined,
fork icon0
star icon0
watch icon1

+ 6 other calls in file

Other functions in date-fns

Sorted by popularity

function icon

date-fns.format is the most popular function in date-fns (3838 examples)