date-fns#parseISO JavaScript Examples

The following examples show how to use date-fns#parseISO. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.js    From lnft with GNU Affero General Public License v3.0 7 votes vote down vote up
canAccept = ({ type, artwork, created_at, accepted }, debug) => {
  let $user = get(user);
  if (accepted) return false;

  let isOwner = ({ owner }) => $user && $user.id === owner.id;

  let underway = ({ auction_start: s, auction_end: e }) =>
    e && isWithinInterval(new Date(), { start: parseISO(s), end: parseISO(e) });

  return (
    artwork &&
    isCurrent(artwork, created_at, type) &&
    isOwner(artwork) &&
    !underway(artwork)
  );
}
Example #2
Source File: helpers.js    From monsuivipsy with Apache License 2.0 6 votes vote down vote up
formatDateThread = (date) => {
  const isoDate = parseISO(date);
  if (isToday(isoDate)) {
    return "Aujourd'hui";
  } else if (isYesterday(isoDate)) {
    return "Hier";
  } else {
    const formattedDate = format(isoDate, "EEEE d MMMM", { locale: fr });
    return firstLetterUppercase(formattedDate);
  }
}
Example #3
Source File: index.js    From ftx-cli with MIT License 6 votes vote down vote up
function calculateMillisecondsUntilDate(date) {
  const currentDate = new Date();
  const scheduleDate = parseISO(date);

  if (!isValid(scheduleDate)) {
    return null;
  }

  if (isBefore(scheduleDate, currentDate)) {
    return null;
  }

  return differenceInMilliseconds(scheduleDate, currentDate);
}
Example #4
Source File: request.js    From ftx-cli with MIT License 6 votes vote down vote up
async function setServerTimeOffset(options) {
  const startMilliseconds = Date.now();
  const serverTime = await request(time.getServerTime(options));
  const endMilliseconds = Date.now();
  const serverMilliseconds = parseISO(serverTime).getTime();

  serverTimeOffsetMilliseconds = calculateServerTimeOffset(
    serverMilliseconds,
    startMilliseconds,
    endMilliseconds
  );
}
Example #5
Source File: Item.jsx    From killed-by-microsoft with MIT License 6 votes vote down vote up
getYears() {
    const { dateClose, dateOpen } = this.props;
    const duration = formatDistance(parseISO(dateClose), parseISO(dateOpen));

    if (this.isPast()) {
      return ` It was ${duration} old.`;
    }
    return ` It will be ${duration} old.`;
  }
Example #6
Source File: Item.jsx    From killed-by-microsoft with MIT License 6 votes vote down vote up
ageRange(grave) {
    const monthOpen = format(parseISO(grave.dateClose), 'LLLL');
    const yearOpen = format(parseISO(grave.dateOpen), 'uuuu');
    const yearClose = format(parseISO(grave.dateClose), 'uuuu');
    if (!this.isPast()) {
      const date = parseISO(grave.dateClose);
      return (
        <AgeRange>
          <time dateTime={format(date, 'uuuu-LL-dd')}>
            {monthOpen}
            <br />
            {format(date, 'uuuu')}
          </time>
        </AgeRange>
      );
    }
    return (
      <AgeRange>
        <time dateTime={format(parseISO(grave.dateOpen), 'uuuu-LL-dd')}>
          {yearOpen}
        </time>
        {' - '}
        <time dateTime={format(parseISO(grave.dateClose), 'uuuu-LL-dd')}>
          {yearClose}
        </time>
      </AgeRange>
    );
  }
Example #7
Source File: monitor.js    From lnft with GNU Affero General Public License v3.0 6 votes vote down vote up
isSpent = async ({ ins }, artwork_id) => {
  try {
    let { transactions } = await q(getLastTransaction, { artwork_id });

    if (
      !transactions.length ||
      compareAsc(
        parseISO(transactions[0].created_at),
        subMinutes(new Date(), 2)
      ) > 0
    )
      return false;

    for (let i = 0; i < ins.length; i++) {
      let { index, hash } = ins[i];
      let txid = reverse(hash).toString("hex");

      let { spent } = await electrs
        .url(`/tx/${txid}/outspend/${index}`)
        .get()
        .json();

      if (spent) return true;
    }

    return false;
  } catch (e) {
    console.log("problem checking spent status", e);
    return false;
  }
}
Example #8
Source File: utils.js    From lnft with GNU Affero General Public License v3.0 6 votes vote down vote up
underway = ({ auction_start: s, auction_end: e }) =>
  e && isWithinInterval(new Date(), { start: parseISO(s), end: parseISO(e) })
Example #9
Source File: TransactionsTable.js    From actual with MIT License 6 votes vote down vote up
function serializeTransaction(transaction, showZeroInDeposit, dateFormat) {
  let { amount, date } = transaction;

  if (isPreviewId(transaction.id)) {
    amount = getScheduledAmount(amount);
  }

  let debit = amount < 0 ? -amount : null;
  let credit = amount > 0 ? amount : null;

  if (amount === 0) {
    if (showZeroInDeposit) {
      credit = 0;
    } else {
      debit = 0;
    }
  }

  // Validate the date format
  if (!isDateValid(parseISO(date))) {
    // Be a little forgiving if the date isn't valid. This at least
    // stops the UI from crashing, but this is a serious problem with
    // the data. This allows the user to go through and see empty
    // dates and manually fix them.
    date = null;
  }

  return {
    ...transaction,
    date,
    debit: debit != null ? integerToCurrency(debit) : '',
    credit: credit != null ? integerToCurrency(credit) : ''
  };
}
Example #10
Source File: SimpleTransactionsTable.js    From actual with MIT License 6 votes vote down vote up
function serializeTransaction(transaction, dateFormat) {
  let { date } = transaction;

  if (!isDateValid(parseISO(date))) {
    date = null;
  }

  return {
    ...transaction,
    date: date ? formatDate(parseISO(date), dateFormat) : null
  };
}
Example #11
Source File: utils.js    From lnft with GNU Affero General Public License v3.0 6 votes vote down vote up
isCurrent = ({ transferred_at: t }, created_at, type) =>
  type === "bid" && (!t || compareAsc(parseISO(created_at), parseISO(t)) > 0)
Example #12
Source File: helpers.js    From monsuivipsy with Apache License 2.0 6 votes vote down vote up
formatRelativeDate = (date) => {
  const isoDate = parseISO(date);
  if (isToday(isoDate)) {
    return "aujourd'hui";
  } else if (isYesterday(isoDate)) {
    return "hier";
  } else {
    return format(isoDate, "EEEE d MMMM", { locale: fr });
  }
}
Example #13
Source File: survey-data.js    From monsuivipsy with Apache License 2.0 6 votes vote down vote up
alertNoDataYesterday = ({ date, diaryData, navigation }) => {
  if (isToday(parseISO(date)) && !diaryData[formatDay(beforeToday(1))]) {
    Alert.alert("Souhaitez-vous remplir votre questionnaire pour hier ?", "", [
      {
        text: "Oui, je le renseigne maintenant",
        onPress: () => {
          logEvents.logFeelingStartYesterday(true);
          startAtFirstQuestion(formatDay(beforeToday(1)), navigation);
        },
        style: "default",
      },
      {
        text: "Plus tard",
        onPress: () => {
          logEvents.logFeelingStartYesterday(false);
        },
        style: "cancel",
      },
    ]);
  }
}
Example #14
Source File: index.jsx    From stream-live-system with MIT License 6 votes vote down vote up
Listlive = ({ lives }) => {
  return (
    <div>
      {
        lives.map((live, index) => (
          <div className="card" key={index}>
            <div className="uuid-live" data-label="UUID">{live.id}</div>
            <div className="title-live" data-label="TITLE">{live.title}</div>
            <div className="date-live" data-label="DATE" >{ format(parseISO(live.created_at), 'dd/MM/yyyy HH:mm')}</div>
            <div className="create-link-live effect-in" data-label="CREATE LIVE"> <a target="_blank" rel="noopener noreferrer" href={`http://localhost:4000/broadcaster/${live.slug}`}>create live</a> </div>
            <div className="invite-live effect-in" data-label="INVITE"> <a target="_blank" rel="noopener noreferrer" href={`http://localhost:4000/viewer/${live.slug}`}>invite</a> </div>
            <div className="status-live" data-label="STATUS">
              <div className="circle-status-live" style={{ backgroundColor: live.status === 'pending' ? 'rgb(255, 208, 86)' : 'red' }}></div>
            </div>
          </div>
          )
        )
      }
    </div>
  )
}
Example #15
Source File: RealtimeChart.js    From umami with MIT License 6 votes vote down vote up
function mapData(data) {
  let last = 0;
  const arr = [];

  data.reduce((obj, val) => {
    const { created_at } = val;
    const t = startOfMinute(parseISO(created_at));
    if (t.getTime() > last) {
      obj = { t: format(t, 'yyyy-LL-dd HH:mm:00'), y: 1 };
      arr.push(obj);
      last = t;
    } else {
      obj.y += 1;
    }
    return obj;
  }, {});

  return arr;
}
Example #16
Source File: useDateRange.js    From umami with MIT License 6 votes vote down vote up
export default function useDateRange(websiteId) {
  const { locale } = useLocale();
  const forceUpdate = useForceUpdate();
  const selector = useCallback(state => state?.[websiteId]?.dateRange, [websiteId]);
  const websiteDateRange = useStore(selector);
  const defaultDateRange = useMemo(() => getDateRange(DEFAULT_DATE_RANGE, locale), [locale]);

  const globalDefault = getItem(DATE_RANGE_CONFIG);
  let globalDateRange;

  if (globalDefault) {
    if (typeof globalDefault === 'string') {
      globalDateRange = getDateRange(globalDefault, locale);
    } else if (typeof globalDefault === 'object') {
      globalDateRange = {
        ...globalDefault,
        startDate: parseISO(globalDefault.startDate),
        endDate: parseISO(globalDefault.endDate),
      };
    }
  }

  function saveDateRange(dateRange) {
    if (websiteId) {
      setDateRange(websiteId, dateRange);
    } else {
      setItem(DATE_RANGE_CONFIG, dateRange);
      forceUpdate();
    }
  }

  return [websiteDateRange || globalDateRange || defaultDateRange, saveDateRange];
}
Example #17
Source File: date-time.js    From tisn.app with GNU Affero General Public License v3.0 6 votes vote down vote up
formatUtcToTimeZone = (dateString, formatString) =>
  format(
    utcToZonedTime(
      parseISO(dateString),
      Intl.DateTimeFormat().resolvedOptions().timeZone
    ),
    formatString,
    {
      locale: getLocale(),
    }
  )
Example #18
Source File: date-time.js    From tisn.app with GNU Affero General Public License v3.0 5 votes vote down vote up
formatDate = (dateString) =>
  format(parseISO(dateString.split('T')[0]), 'P', {
    locale: getLocale(),
  })
Example #19
Source File: wallet.js    From lnft with GNU Affero General Public License v3.0 5 votes vote down vote up
isMultisig = ({ has_royalty, auction_end }) => {
  return !!(
    (auction_end && compareAsc(parseISO(auction_end), new Date()) > 0) ||
    has_royalty
  );
}
Example #20
Source File: index.jsx    From stream-live-system with MIT License 5 votes vote down vote up
ContainerVideo = ({ videoRef, countViews, titleVideo, live }) => {
  const isDone = live && live.status === 'done';

  if (videoRef) {
    document.getElementById('video')
    .srcObject = videoRef; 
  }
  
  return (
    <div className="video">
      <div className="responsive-video">
        <video 
          width="1000" 
          height="600" 
          id='video' 
          autoPlay 
          muted 
          controls 
        />
      </div>
      <div className="title-video">
        { 
          `${ 
            isDone 
            ? `${titleVideo} made in - ${
              format(parseISO(live.created_at), 
              "dd/MM/yyyy HH:mm")}` 
            : 
            `${titleVideo}` 
          }` 
        } 
      </div>
      <div className="countViews">
        { 
          `${ 
            !isDone 
            ? `Views ${ countViews }` 
            : '' 
            }` 
        }
      </div>
    </div>
  )
}
Example #21
Source File: artworks.js    From lnft with GNU Affero General Public License v3.0 5 votes vote down vote up
app.post("/transaction", auth, async (req, res) => {
  try {
    const { transaction } = req.body;

    let { artworks } = await q(getTransactionArtwork, {
      id: transaction.artwork_id,
    });
    let {
      id: artwork_id,
      bid_increment,
      auction_end,
      auction_start,
      owner,
      title,
      bid,
      slug,
    } = artworks[0];

    if (
      bid &&
      transaction.type === "bid" &&
      transaction.amount < bid.amount + bid_increment &&
      auction_end &&
      compareAsc(parseISO(auction_end), new Date()) > 0
    ) {
      throw new Error(
        `Minimum bid is ${((bid.amount + bid_increment) / 100000000).toFixed(
          8
        )}`
      );
    }

    if (transaction.type === "purchase") {
      let { id: owner_id } = await getUser(req);
      await q(setOwner, { id: artwork_id, owner_id });
    }

    let locals = {
      outbid: false,
      title,
      url: `${SERVER_URL}/a/${slug}`,
    };

    try {
      await mail.send({
        template: "notify-bid",
        locals,
        message: {
          to: owner.display_name,
        },
      });

      if (bid && bid.user) {
        locals.outbid = true;

        await mail.send({
          template: "notify-bid",
          locals,
          message: {
            to: bid.user.display_name,
          },
        });
      }
    } catch (err) {
      console.error("Unable to send email");
      console.error(err);
    }

    let result = await api(req.headers)
      .post({ query: createTransaction, variables: { transaction } })
      .json();

    if (result.errors) throw new Error(result.errors[0].message);

    res.send(result.data.insert_transactions_one);
  } catch (e) {
    console.log("problem creating transaction", e);
    res.code(500).send(e.message);
  }
});
Example #22
Source File: DrawLastUpdated.js    From covid19japan with MIT License 5 votes vote down vote up
drawLastUpdated = (lastUpdatedString, currentLanguage) => {
  // Draw the last updated time
  // If this is called before data is loaded, lastUpdated can be null.
  if (!lastUpdatedString) {
    return;
  }

  const display = document.getElementById("last-updated-time");
  if (!display) {
    return;
  }

  let lastUpdated;
  try {
    lastUpdated = parseISO(lastUpdatedString);
    // If the timestamp is not ISO, fall back on the old date format
    // TODO: remove after ISO time format is fully deployed
    if (lastUpdated === "Invalid Date") {
      lastUpdated = parse(
        lastUpdatedString.slice(0, -4),
        TIME_FORMAT,
        new Date()
      );
    }
  } catch (e) {
    // Fall back to raw value on failed parse
    display.textContent = lastUpdatedString;
    return;
  }

  for (const language of LANGUAGES) {
    addRelativeTimeLocalization(lastUpdated, language);
  }

  display.setAttribute("title", lastUpdatedString);
  display.setAttribute("data-i18n", "last-updated-time");
  display.textContent = i18next.getResource(
    currentLanguage,
    "translation",
    "last-updated-time"
  );
}
Example #23
Source File: Item.jsx    From killed-by-microsoft with MIT License 5 votes vote down vote up
timePhrase() {
    const { dateClose } = this.props;
    const relativeDate = formatDistanceToNow(parseISO(dateClose), new Date());
    if (!this.isPast()) {
      return <span>{`${soonToDieIdiom()} in ${relativeDate}, `}</span>;
    }
    return <span>{`Killed ${relativeDate} ago, `}</span>;
  }
Example #24
Source File: post.js    From ebpf.io-website with Creative Commons Attribution 4.0 International 5 votes vote down vote up
formatPostDate = post =>
  format(parseISO(post.frontmatter.date), "MMMM d, yyyy")
Example #25
Source File: date-formater.js    From next-tina-blog-starter with MIT License 5 votes vote down vote up
export default function DateFormater({ dateString }) {
  const date = parseISO(dateString)
  return <time dateTime={dateString}>{format(date, 'LLLL	d, yyyy')}</time>
}
Example #26
Source File: date-time.js    From tisn.app with GNU Affero General Public License v3.0 5 votes vote down vote up
distanceToNow = (dateTimeString) =>
  formatDistanceToNow(parseISO(dateTimeString), { locale: getLocale() })
Example #27
Source File: DatePicker.js    From basis with MIT License 5 votes vote down vote up
DEFAULT_PROPS = {
  color: InternalInput.DEFAULT_PROPS.color,
  dayMode: "2-digits",
  yearMode: "4-digits",
  disabled: false,
  optional: false,
  validate: (value, { isEmpty, dayMode, yearMode }) => {
    if (isEmpty(value)) {
      return "Required";
    }

    const { day, month, year } = value;
    const errors = [];

    if (dayMode === "2-digits") {
      if (DAY_REGEX.test(day) === false) {
        errors.push("Day must be within 1-31.");
      }
    }

    if (MONTH_REGEX.test(month) === false) {
      errors.push("Month must be within 1-12.");
    }

    if (yearMode === "2-digits") {
      if (TWO_DIGITS_YEAR_REGEX.test(year) === false) {
        errors.push("Year must be within 00-99.");
      }
    } else {
      if (FOUR_DIGITS_YEAR_REGEX.test(year) === false) {
        errors.push("Year must be within 1900-2199.");
      }
    }

    if (dayMode === "2-digits" && errors.length === 0) {
      const twoDigitsDay = day.length === 1 ? `0${day}` : day;
      const twoDigitsMonth = month.length === 1 ? `0${month}` : month;

      if (
        isDateValid(
          parseISO(
            `${
              yearMode === "2-digits" ? `20${year}` : year
            }-${twoDigitsMonth}-${twoDigitsDay}`
          )
        ) === false
      ) {
        errors.push("Invalid date.");
      }
    }

    return errors;
  },
}
Example #28
Source File: index.js    From monsuivipsy with Apache License 2.0 5 votes vote down vote up
canEdit = (d) => {
  const limitDate = beforeToday(7);
  const canEditBool = compareAsc(parseISO(d), limitDate) === 1;
  return canEditBool;
}
Example #29
Source File: transaction.js    From actual with MIT License 5 votes vote down vote up
function serializeTransaction(transaction, dateFormat) {
  let { date, amount } = transaction;
  return {
    ...transaction,
    date: formatDate(parseISO(date), dateFormat),
    amount: integerToAmount(amount || 0)
  };
}