luxon#DateTime TypeScript Examples

The following examples show how to use luxon#DateTime. 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.ts    From posthog-foss with MIT License 7 votes vote down vote up
export function generateKafkaPersonUpdateMessage(
    createdAt: DateTime | string,
    properties: Properties,
    teamId: number,
    isIdentified: boolean,
    id: string,
    version: number | null,
    isDeleted = 0
): ProducerRecord {
    return {
        topic: KAFKA_PERSON,
        messages: [
            {
                value: Buffer.from(
                    JSON.stringify({
                        id,
                        created_at: castTimestampOrNow(createdAt, TimestampFormat.ClickHouseSecondPrecision),
                        properties: JSON.stringify(properties),
                        team_id: teamId,
                        is_identified: isIdentified,
                        is_deleted: isDeleted,
                        ...(version ? { version } : {}),
                    })
                ),
            },
        ],
    }
}
Example #2
Source File: utils.ts    From programmer-fa with MIT License 7 votes vote down vote up
hasUserRegisteredRecently = (tweet: any): boolean => {
  const originalUser: any = tweet.user;
  const retweeterUser: any = tweet.retweeted_status;

  const originalUserRegisterDate: DateTime = parseTwitterDateToLuxon(originalUser.created_at);

  let retweeterUserRegisterDateDiff: number;

  const dayToBlockNewUsers: number = +envs.IGNORE_USERS_NEWER_THAN;

  const originalUserRegisterDateDiff = getDiffBetweenDateTimeAndNowInDays(
    originalUserRegisterDate,
  ).days;

  if (retweeterUser) {
    const retweeterUserRegisterDate: DateTime = parseTwitterDateToLuxon(tweet.retweeted_status.user.created_at);

    retweeterUserRegisterDateDiff = getDiffBetweenDateTimeAndNowInDays(
      retweeterUserRegisterDate,
    ).days;
  }

  return (
    dayToBlockNewUsers > originalUserRegisterDateDiff
    || dayToBlockNewUsers > retweeterUserRegisterDateDiff
  );
}
Example #3
Source File: utils.tsx    From backstage with Apache License 2.0 7 votes vote down vote up
function formatDateTimeShort(milliseconds: number) {
  if ((milliseconds as any) === 'auto') {
    // When recharts gets confused (empty data)
    return '';
  }
  return DateTime.fromMillis(milliseconds).toLocaleString(
    DateTime.DATETIME_SHORT,
  );
}
Example #4
Source File: functions.ts    From keycaplendar with MIT License 6 votes vote down vote up
getSetMonthRange = (
  sets: (SetType | StatisticsSetType)[],
  prop: DateSortKeys,
  format: string
): string[] => {
  const setMonths = removeDuplicates(
    sets.map((set) => {
      const val = set[prop];
      return val && !val.includes("Q")
        ? DateTime.fromISO(val).toFormat("yyyy-MM")
        : "";
    })
  ).filter(Boolean);
  alphabeticalSort(setMonths);
  const monthDiff = (dateFrom: DateTime, dateTo: DateTime) => {
    return dateTo.month - dateFrom.month + 12 * (dateTo.year - dateFrom.year);
  };
  const length =
    monthDiff(
      DateTime.fromISO(setMonths[0], { zone: "utc" }),
      DateTime.fromISO(setMonths[setMonths.length - 1], { zone: "utc" })
    ) + 1;
  const allMonths = Array(length)
    .fill("")
    .map((v, i) =>
      DateTime.fromISO(setMonths[0], { zone: "utc" })
        .plus({ months: i })
        .toFormat(format)
    );
  return allMonths;
}
Example #5
Source File: web.ts    From Wikitext-VSCode-Extension with MIT License 6 votes vote down vote up
private async fetchArchive(): Promise<void> {
        // Fetch content and archive in parallel
        const websiteResponse: Promise<Response> = fetch(this.url);
        const archiveResponse: Promise<Response> = fetch(this.archiveApiUrl);
        const results: [Response, Response] = await Promise.all([websiteResponse, archiveResponse]);

        const websiteText: string = await results[0].text();
        this.metaData = cheerio.load(websiteText);

        const archiveJSON = await results[1].json();
        const re: ArchiveResult = ArchiveConvert.toArchiveResult(archiveJSON);

        // Check archive and get the closest
        if (re.archivedSnapshots.closest) {
            this.archivedUrl = re.archivedSnapshots.closest.url;
            this.archivedDate = DateTime.fromFormat(re.archivedSnapshots.closest.timestamp, "yyyyMMddhhmmss").toISODate();
        }
    }
Example #6
Source File: Timestamp.tsx    From spotify-recently-played-readme with MIT License 6 votes vote down vote up
/**
 * Timestamp component of a track.
 */
export default function Timestamp(props: Props): JSX.Element {
    const { isoDate } = props;

    // Set timestamp text
    const timestampText =
        DateTime.fromISO(isoDate, {
            zone: 'utc',
        }).toRelative({
            style: 'short',
        }) ?? '';

    const timestampTitle = isoDate;

    return (
        <>
            <Text className="timestamp" type="secondary" title={timestampTitle}>
                {timestampText}
            </Text>
        </>
    );
}
Example #7
Source File: update-person-properties.benchmark.ts    From posthog-foss with MIT License 6 votes vote down vote up
async function runUpdateCycle(
    hub: Hub,
    teamId: number,
    startingProperties: Record<string, any>,
    propertyUpdates: Record<string, any>,
    propertyToOperationMap: Record<string, PropertyUpdateOperation>,
    isControl = false
): Promise<number> {
    const uuid = new UUIDT().toString()
    const distinctId = String(Math.random() + Math.random())
    const person = await hub.db.createPerson(DateTime.now(), startingProperties, teamId, null, false, uuid, [
        distinctId,
    ])

    const startTime = performance.now()
    if (isControl) {
        await hub.db.updatePerson(person, { properties: propertyUpdates })
    } else {
        await hub.db.updatePersonProperties(person, propertyUpdates, propertyToOperationMap, new Date().toISOString())
    }
    const endTime = performance.now()
    return endTime - startTime
}
Example #8
Source File: api.ts    From abrechnung with GNU Affero General Public License v3.0 6 votes vote down vote up
export async function refreshToken() {
    const token = localStorage.getItem("access_token");
    if (
        token == null ||
        String(token) === "null" ||
        String(token) === "undefined" ||
        DateTime.fromSeconds(JSON.parse(atob(token.split(".")[1])).exp) <= DateTime.now().plus({ minutes: 1 })
    ) {
        const sessionToken = localStorage.getItem("session_token");
        if (sessionToken == null) {
            return Promise.reject("cannot refresh access token");
        }
        const resp = await bareApi.post("/auth/fetch_access_token", {
            token: sessionToken,
        });
        setAccessToken(resp.data.access_token);
    }
}
Example #9
Source File: pathofexile-bulk.ts    From awakened-poe-trade with MIT License 6 votes vote down vote up
function toPricingResult (
  result: FetchResult,
  opts: { accountName: string },
  offer: number
): PricingResult {
  return {
    id: result.id,
    relativeDate: DateTime.fromISO(result.listing.indexed).toRelative({ style: 'short' }) ?? '',
    exchangeAmount: result.listing.offers[offer].exchange.amount,
    itemAmount: result.listing.offers[offer].item.amount,
    stock: result.listing.offers[offer].item.stock,
    isMine: (result.listing.account.name === opts.accountName),
    ign: result.listing.account.lastCharacterName,
    accountName: result.listing.account.name,
    accountStatus: result.listing.account.online
      ? (result.listing.account.online.status === 'afk' ? 'afk' : 'online')
      : 'offline'
  }
}
Example #10
Source File: CashImportService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
private buildTransactionDate(
        oneLine: string[],
        csvConfig: CashImportConfigDetails,
        currentLine: number,
    ): Date | null {
        const config = csvConfig.converting.property.transactionDate;
        if (!config) {
            return null;
        }
        if (oneLine.length < config.index) {
            throw new CashError(
                // tslint:disable-next-line:max-line-length
                `Line ${currentLine}: Not enough columns to get transaction date. Impossible to access column n°${config.index} because only ${oneLine.length} columns are available.`,
            );
        }
        try {
            const value: string = oneLine[config.index - 1];
            const luxonDate = DateTime.fromFormat(value, config.format);
            return luxonDate.toJSDate();
        } catch (e) {
            throw new CashError(`Line ${currentLine}: Can't build transaction date: ${e.message}`);
        }
    }
Example #11
Source File: dateUtils.ts    From airmessage-web with Apache License 2.0 6 votes vote down vote up
//Used in read receipts
export function getDeliveryStatusTime(date: Date): string {
	const dateNow = new Date();
	const luxon = DateTime.fromJSDate(date);
	const formattedTime = luxon.toLocaleString(DateTime.TIME_SIMPLE)!;
	
	//Same day (12:30)
	if(checkSameDay(date, dateNow)) {
		return formattedTime;
	}
	
	//Yesterday (Yesterday)
	{
		const compareDate = new Date(dateNow.getFullYear(), dateNow.getMonth(), dateNow.getDate() - 1); //Today (now) -> Yesterday
		if(checkSameDay(date, compareDate)) {
			return "Yesterday";
		}
	}
	
	//Same 7-day period (Sunday)
	{
		const compareDate = new Date(dateNow.getFullYear(), dateNow.getMonth(), dateNow.getDate() - 7); //Today (now) -> One week ago
		if(compareDates(date, compareDate) > 0) {
			return luxon.toFormat("cccc");
		}
	}
	
	//Same year (Dec 9)
	{
		const compareDate = new Date(dateNow.getFullYear() - 1, dateNow.getMonth(), dateNow.getDate()); //Today (now) -> One year ago
		if(compareDates(date, compareDate) > 0) {
			return luxon.toFormat("LLL d");
		}
	}
	
	//Different years (Dec 9, 2018)
	return luxon.toFormat("LLL d, yyyy") + bulletSeparator + formattedTime;
}
Example #12
Source File: utils.ts    From programmer-fa with MIT License 6 votes vote down vote up
parseTwitterDateToLuxon = (date: string): DateTime => (
  DateTime.fromFormat(date, 'ccc LLL dd HH:mm:ss ZZZ yyyy')
)
Example #13
Source File: ServerTokenManager.ts    From backstage with Apache License 2.0 6 votes vote down vote up
async getToken(): Promise<{ token: string }> {
    if (!this.verificationKeys.length) {
      await this.generateKeys();
    }

    if (this.currentTokenPromise) {
      return this.currentTokenPromise;
    }

    const result = Promise.resolve().then(async () => {
      const jwt = await new SignJWT({})
        .setProtectedHeader({ alg: TOKEN_ALG })
        .setSubject(TOKEN_SUB)
        .setExpirationTime(
          DateTime.now().plus(TOKEN_EXPIRY_AFTER).toUnixInteger(),
        )
        .sign(this.signingKey);
      return { token: jwt };
    });

    this.currentTokenPromise = result;

    result
      .then(() => {
        setTimeout(() => {
          this.currentTokenPromise = undefined;
        }, TOKEN_REISSUE_AFTER.toMillis());
      })
      .catch(() => {
        this.currentTokenPromise = undefined;
      });

    return result;
  }
Example #14
Source File: statistics.ts    From keycaplendar with MIT License 5 votes vote down vote up
today = DateTime.utc()
Example #15
Source File: web.ts    From Wikitext-VSCode-Extension with MIT License 5 votes vote down vote up
private setPublishedDate(): void {
        const date: string | undefined =
            this.getAttr("meta[property='article:published_time']") ||
            this.getAttr("time", "datetime");
        if (date) {
            this.publishDate = DateTime.fromISO(date).toISODate();
        }
    }
Example #16
Source File: mmdb.ts    From posthog-foss with MIT License 5 votes vote down vote up
export async function prepareMmdb(
    serverInstance: MMDBPrepServerInstance,
    onlyBackground = false
): Promise<ReaderModel | null | boolean> {
    const { hub } = serverInstance
    const { db } = hub

    const readResults = await db.postgresQuery<PluginAttachmentDB>(
        `
        SELECT * FROM posthog_pluginattachment
        WHERE key = $1 AND plugin_config_id IS NULL AND team_id IS NULL
        ORDER BY file_name ASC
    `,
        [MMDB_ATTACHMENT_KEY],
        'fetchGeoIpAttachment'
    )
    if (!readResults.rowCount) {
        status.info('⬇️', `Fetching ${MMDB_ATTACHMENT_KEY} for the first time`)
        if (onlyBackground) {
            await backgroundInjectFreshMmdb(serverInstance)
            return true
        } else {
            const mmdb = await distributableFetchAndInsertFreshMmdb(serverInstance)
            if (!mmdb) {
                status.warn('?', 'Because of MMDB unavailability, GeoIP plugins will fail in this PostHog instance')
            }
            return mmdb
        }
    }
    const [mmdbRow] = readResults.rows
    if (!mmdbRow.contents) {
        throw new Error(`${MMDB_ATTACHMENT_KEY} attachment ID ${mmdbRow.id} has no file contents!`)
    }

    const mmdbDateStringMatch = mmdbRow.file_name.match(/\d{4}-\d{2}-\d{2}/)
    if (!mmdbDateStringMatch) {
        throw new Error(
            `${MMDB_ATTACHMENT_KEY} attachment ID ${mmdbRow.id} has an invalid filename! ${MMDB_ATTACHMENT_KEY} filename must include an ISO date`
        )
    }
    const mmdbAge = Math.round(-DateTime.fromISO(mmdbDateStringMatch[0]).diffNow().as('days'))
    if (mmdbAge > MMDB_STALE_AGE_DAYS) {
        status.info(
            '?',
            `${MMDB_ATTACHMENT_KEY} is ${mmdbAge} ${
                mmdbAge === 1 ? 'day' : 'days'
            } old, which is more than the staleness threshold of ${MMDB_STALE_AGE_DAYS} days, refreshing in the background...`
        )
        if (onlyBackground) {
            await backgroundInjectFreshMmdb(serverInstance)
            return true
        } else {
            void backgroundInjectFreshMmdb(serverInstance)
        }
    }

    if (onlyBackground) {
        return false
    } else {
        return await decompressAndOpenMmdb(mmdbRow.contents, mmdbRow.file_name)
    }
}