moment#Moment TypeScript Examples

The following examples show how to use moment#Moment. 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 nldates-obsidian with MIT License 7 votes vote down vote up
export async function getOrCreateDailyNote(date: Moment): Promise<TFile | null> {
  // Borrowed from the Slated plugin:
  // https://github.com/tgrosinger/slated-obsidian/blob/main/src/vault.ts#L17
  const desiredNote = getDailyNote(date, getAllDailyNotes());
  if (desiredNote) {
    return Promise.resolve(desiredNote);
  }
  return createDailyNote(date);
}
Example #2
Source File: utils.tsx    From next-basics with GNU General Public License v3.0 7 votes vote down vote up
getDate = (year: number, month: number, day = 1): Moment => {
  let _year = year;
  let _month = month;
  let _day = day;
  // 如果 month 不在1-12之间,则顺推为前后年的月份
  if (month > 12) {
    _year++;
    _month = month - 12;
  } else if (month < 1) {
    _year--;
    _month = 12 - month;
  }
  // 如果 day 大于当天月份的总天数,则day的值为当天月份的总天数
  const curMonthDays = moment(`${_year}-${_month}`).daysInMonth();
  if (day > curMonthDays) {
    _day = curMonthDays;
  }
  return moment(`${_year}-${_month}-${_day}`);
}
Example #3
Source File: utils.ts    From erda-ui with GNU Affero General Public License v3.0 7 votes vote down vote up
transformRange = (v: ITimeRange, format = defaultFormat) => {
  let dateStr;
  let dateArr: Moment[] = [];
  if (v.mode === 'quick' && v.quick) {
    dateStr = relativeTimeRange[v.quick];
    const [unit, count] = v.quick?.split(':') || [];
    if (unit) {
      dateArr = translateRelativeTime(unit, parseInt(count, 10));
    }
  } else if (v.mode === 'customize') {
    const { start, end } = v.customize;
    if (start && end) {
      dateStr = `${start.format(format)} - ${end.format(format)}`;
      dateArr = [start, end];
    }
  }
  return {
    date: dateArr,
    dateStr,
  };
}
Example #4
Source File: utils.ts    From datart with Apache License 2.0 7 votes vote down vote up
formatControlDateToStr = (config: ControllerConfig) => {
  if (config.controllerDate) {
    const filterDate = config.controllerDate;
    if (filterDate.startTime && filterDate.startTime.exactValue) {
      if ((filterDate.startTime.exactValue as Moment).format) {
        let exactTime = filterDate.startTime.exactValue as Moment;
        let newExactTime = exactTime.format(TIME_FORMATTER);
        config.controllerDate.startTime.exactValue = newExactTime;
      }
    }
    if (filterDate.endTime && filterDate.endTime.exactValue) {
      if ((filterDate.endTime.exactValue as Moment).format) {
        let exactTime = filterDate.endTime.exactValue as Moment;
        let newExactTime = exactTime.format(TIME_FORMATTER);
        config.controllerDate.endTime!.exactValue = newExactTime;
      }
    }
  }
  return config;
}
Example #5
Source File: InputDate.tsx    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
InputDate = ({
  onChange,
  value,
  text = null,
  width = 200,
  isValidDate = (date: Moment) => true,
}) => (
  <div>
    <Label width={width}>{text}</Label>
    <Date
      value={value}
      onChange={onChange}
      dateFormat="DD/MM/YYYY"
      timeFormat={false}
      width={width}
      isValidDate={isValidDate}
    />
  </div>
)
Example #6
Source File: native_queries.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
validatorStats = (address: string, startBlock = -1, endBlock = -1, startTime: Moment, endTime: Moment, page = 1, countQuery = false): string => 
`select 
	${countQuery ? ' count(vs."eraId")::integer as "totalCount" ' : ` vs."eraId" as id, 
    stake_total as "stakeTotal", 
    stake_own as "stakeOwn", 
    points, 
    rewards, 
    commission, 
    subq2.blocks_cnt as "blocksCount" `}
from 
	validator_stats vs 
inner join 
	accounts a on a.id = vs."accountId" 
${countQuery ? '' : `inner join 
	(select 
		"eraId", count(b.id) blocks_cnt 
	from 
		blocks b 
	${address != '' ? ` where b."validatorId" in (select id from accounts where key = '${address}') ` : ''}
	    group by "eraId") subq2 
	on 
		subq2."eraId" = vs."eraId"`} 
where ${address != '' ? `a.key = '${address}' and ` : ''}
	vs."eraId" in 
	(select 
        subq.era 
    from 
        (select 
            distinct("eraId") era 
        from blocks 
        where ${startBlock > 0 ? ` blocks.id >= ${startBlock} and blocks.id <= ${endBlock} ` : '1 = 1'} 
        ${startTime ? ` AND blocks.timestamp >= '${startTime.toISOString()}'::date and blocks.timestamp <= '${endTime.toISOString()}'::date ` : ''}) subq
        ) ${countQuery ? '' : ` order by id limit ${pageSize} offset ${pageSize * (page - 1)} `}`
Example #7
Source File: downloaded_image.ts    From SpaceEye with MIT License 6 votes vote down vote up
/**
 * Format timestamp used in image file names.
 *
 * @param timestamp - Timestamp to format
 * @returns Formatted timestamp
 */
function formatTimestamp(timestamp: Moment): string {
    return timestamp.valueOf().toString()
}
Example #8
Source File: datetime.ts    From SQForm with MIT License 6 votes vote down vote up
/**
 * Converts a date/time on the client to be in the proper format for the server. Accepts a string or Moment object.
 * Defaults to a new Moment object with date/time set to now.
 *
 * @param {Moment|string} [dateTime=moment()] - The date/time on the client to convert for server
 * @param {string} fromFormat - The format to convert from (if moment needs a hint to convert)
 * @returns {string} The date/time as a utc ISO string
 */
export function getDateWithoutTimezone(
  dateTime: Moment | string,
  fromFormat: string
): string {
  if (!dateTime) {
    dateTime = moment();
  }

  const momentToConvert =
    typeof dateTime === 'string' ? moment(dateTime, fromFormat) : dateTime;

  return momentToConvert.toISOString();
}
Example #9
Source File: GeneralDatePicker.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
export function GeneralDatePicker(
  props: GeneralDatePickerProps
): React.ReactElement {
  const { name, formElement, value, picker, ...restProps } = props;
  const isDatePicker = picker === "date";
  const format = props.format || (isDatePicker ? "YYYY-MM-DD" : "gggg-ww周");

  const handleChange = (date: moment.Moment, dateString: string): void => {
    props.onChange?.(dateString);
  };

  const handleOk = (date: moment.Moment): void => {
    props.onOk?.(date?.format(props.format));
  };

  return (
    <FormItemWrapper {...props}>
      <InternalStateDatePicker
        {...restProps}
        value={name && formElement ? undefined : value && moment(value, format)}
        format={format}
        onChange={handleChange}
        onOk={isDatePicker ? handleOk : undefined}
        picker={picker}
      />
    </FormItemWrapper>
  );
}
Example #10
Source File: index.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
CommonRangePicker = ({ defaultTime, disabledDate, onOk, ...rest }: IProps) => {
  const [{ value }, updater] = useUpdate({ value: undefined as any });

  React.useEffect(() => {
    const { startTimeMs, endTimeMs } = getTimeSpan(defaultTime);
    updater.value([moment(startTimeMs), moment(endTimeMs)]);
  }, [defaultTime, updater]);

  const defaultDisabledDate = (current: Moment | undefined) => {
    const endEdge = moment();
    const startEdge = moment().subtract(8, 'days');
    return !!current && (current > endEdge || current < startEdge);
  };

  return (
    <RangePicker
      showTime
      style={{ width: 370 }}
      format="YYYY-MM-DD HH:mm:ss"
      allowClear={false}
      placeholder={[i18n.t('common:start time'), i18n.t('common:End time')]}
      onChange={(v: any) => {
        updater.value(v);
        onOk(getTimeSpan(v));
      }}
      value={value as any}
      disabledDate={disabledDate || defaultDisabledDate}
      ranges={getTimeRanges()}
      {...rest}
    />
  );
}
Example #11
Source File: moment-adapter.ts    From angular-material-components with MIT License 6 votes vote down vote up
createDate(year: number, month: number, date: number): Moment {
    // Moment.js will create an invalid date if any of the components are out of bounds, but we
    // explicitly check each case so we can throw more descriptive errors.
    if (month < 0 || month > 11) {
      throw Error(`Invalid month index "${month}". Month index has to be between 0 and 11.`);
    }

    if (date < 1) {
      throw Error(`Invalid date "${date}". Date has to be greater than 0.`);
    }

    const result = this._createMoment({ year, month, date }).locale(this.locale);

    // If the result isn't valid, the date must have been out of bounds for this month.
    if (!result.isValid()) {
      throw Error(`Invalid date "${date}" for month with index "${month}".`);
    }

    return result;
  }
Example #12
Source File: moment-adapter.ts    From ngx-mat-datetime-picker with MIT License 6 votes vote down vote up
createDate(year: number, month: number, date: number): Moment {
    // Moment.js will create an invalid date if any of the components are out of bounds, but we
    // explicitly check each case so we can throw more descriptive errors.
    if (month < 0 || month > 11) {
      throw Error(`Invalid month index "${month}". Month index has to be between 0 and 11.`);
    }

    if (date < 1) {
      throw Error(`Invalid date "${date}". Date has to be greater than 0.`);
    }

    const result = this._createMoment({ year, month, date }).locale(this.locale);

    // If the result isn't valid, the date must have been out of bounds for this month.
    if (!result.isValid()) {
      throw Error(`Invalid date "${date}" for month with index "${month}".`);
    }

    return result;
  }
Example #13
Source File: billing.tsx    From jitsu with MIT License 6 votes vote down vote up
/**
 * Returns the start of current quota period
 * @param subscriptionStart - can be undefined
 */
function getQuotaPeriodStart(subscriptionStart?: string): Moment {
  let quotaPeriodStart
  if (!subscriptionStart) {
    quotaPeriodStart = moment().startOf("month") //first
  } else {
    quotaPeriodStart = moment(subscriptionStart)
    //TODO: if subscription way in the past (annual billing - rewind forward to current month)
  }
  return quotaPeriodStart
}
Example #14
Source File: dailyNotes.ts    From obsidian-calendar-plugin with MIT License 6 votes vote down vote up
/**
 * Create a Daily Note for a given date.
 */
export async function tryToCreateDailyNote(
  date: Moment,
  inNewSplit: boolean,
  settings: ISettings,
  cb?: (newFile: TFile) => void
): Promise<void> {
  const { workspace } = window.app;
  const { format } = getDailyNoteSettings();
  const filename = date.format(format);

  const createFile = async () => {
    const dailyNote = await createDailyNote(date);
    const leaf = inNewSplit
      ? workspace.splitActiveLeaf()
      : workspace.getUnpinnedLeaf();

    await leaf.openFile(dailyNote, { active : true });
    cb?.(dailyNote);
  };

  if (settings.shouldConfirmBeforeCreate) {
    createConfirmationDialog({
      cta: "Create",
      onAccept: createFile,
      text: `File ${filename} does not exist. Would you like to create it?`,
      title: "New Daily Note",
    });
  } else {
    await createFile();
  }
}
Example #15
Source File: index.ts    From ui with GNU Affero General Public License v3.0 6 votes vote down vote up
export class DateType extends AbstractType<Moment> {
  parseValue(raw: string): Moment {
    return moment(JSON.parse(raw))
  }

  parseUrlValue(raw: string): Moment {
    return moment(raw)
  }

  adminFormField(): ComponentType<FieldAdminProps> {
    return dynamic(() => import('./date.admin').then(c => c.DateAdmin));
  }

  inputFormField(): ComponentType<FieldInputProps> {
    return dynamic(() => import('./date.input').then(c => c.builder(this)));
  }
}
Example #16
Source File: collecting.ts    From obsidian-tracker with MIT License 6 votes vote down vote up
// fileBaseName is a string contains dateFormat only
export function getDateFromFilename(
    file: TFile,
    renderInfo: RenderInfo
): Moment {
    // console.log(`getDateFromFilename: ${file.name}`);
    // Get date form fileBaseName

    let fileBaseName = file.basename;

    let dateString = helper.getDateStringFromInputString(
        fileBaseName,
        renderInfo.dateFormatPrefix,
        renderInfo.dateFormatSuffix
    );
    // console.log(dateString);

    let fileDate = helper.strToDate(dateString, renderInfo.dateFormat);
    // console.log(fileDate);

    return fileDate;
}
Example #17
Source File: TimeFilter.tsx    From datart with Apache License 2.0 6 votes vote down vote up
TimeFilter: FC<PresentControllerFilterProps> = memo(
  ({ condition, onConditionChange }) => {
    const [stringTime, setStringTime] = useState<string | undefined>(
      String(condition?.value || ''),
    );

    function onChange(time: Moment | null) {
      const newCondition = updateBy(condition!, draft => {
        draft.value = time?.toString() || '';
      });
      onConditionChange(newCondition);
      setStringTime(newCondition.value as string);
    }
    return <DatePicker value={moment(stringTime)} onChange={onChange} />;
  },
)
Example #18
Source File: native_queries.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
countTotalBlocksProduced = (address: string, startBlock = -1, endBlock = -1, startTime: Moment = null, endTime: Moment = null) => 
`SELECT count(b.id) as "totalBlocks"
FROM blocks b 
INNER JOIN accounts a ON a.id = b."validatorId"
WHERE ${address != '' ? `a.key = '${address}' 
    AND ` : ''} ${startBlock > 0 ? ` b.id >= ${startBlock} AND b.id <= ${endBlock} ` : ' 1=1 '} 
    ${startTime ? ` AND b.timestamp >= '${startTime.toISOString()}'::date AND b.timestamp <= '${endTime.toISOString()}'::date ` : ' AND 1=1 '}`
Example #19
Source File: downloaded_image.ts    From SpaceEye with MIT License 5 votes vote down vote up
constructor(imageId: number, timestamp: Moment, extension: string) {
        this.imageId = imageId
        this.timestamp = timestamp
        this.extension = extension
    }
Example #20
Source File: SQFormDatePickerWithCalendarInputOnly.tsx    From SQForm with MIT License 5 votes vote down vote up
function SQFormDatePickerWithCalendarInputOnly({
  name,
  label,
  size = 'auto',
  isDisabled = false,
  placeholder = '',
  onBlur,
  onChange,
  setDisabledDate,
  muiFieldProps,
}: SQFormDatePickerWithCalendarInputOnlyProps): React.ReactElement {
  const {
    formikField: {helpers},
    fieldHelpers: {handleBlur},
  } = useForm({
    name,
    onBlur,
  });
  const clearButtonClasses = useClearButtonStyles();
  const calendarButtonClasses = useCalendarButtonStyles();
  const {values, setFieldValue} = useFormikContext<{[name: string]: Moment}>();

  const clearField = () => {
    setFieldValue(name, '');
  };

  const handleChange = (date: Moment | null) => {
    helpers.setValue(date);
    onChange && onChange(date);
  };

  return (
    <SQFormDatePicker
      name={name}
      label={label}
      size={size}
      isDisabled={isDisabled}
      placeholder={placeholder}
      onBlur={handleBlur}
      onChange={handleChange}
      setDisabledDate={setDisabledDate}
      isCalendarOnly={true}
      muiFieldProps={muiFieldProps}
      muiTextInputProps={{
        readOnly: true,
        style: {cursor: isDisabled ? 'default' : 'pointer'},
      }}
      InputProps={{
        startAdornment: (
          <IconButton
            classes={clearButtonClasses}
            onClick={clearField}
            disabled={isDisabled || !values[name]}
          >
            <ClearIcon color="disabled" fontSize="small" />
          </IconButton>
        ),
      }}
      InputAdornmentProps={{
        position: 'end',
        classes: calendarButtonClasses,
      }}
    />
  );
}
Example #21
Source File: DatePicker.tsx    From ant-extensions with MIT License 5 votes vote down vote up
DatePicker: React.FC<BaseProps> = React.memo(({ value, onChange }) => {
  const { t } = useTranslation(I18nKey);

  const [_value, setValue] = useState<Moment>();

  useEffect(() => {
    if (value && isDate(value)) {
      setValue(moment(parseDate(value)));
    }
  }, [value]);

  const doUpdate = useCallback((dt: Moment) => {
    setValue(dt);
  }, []);

  const applyDate = useCallback(() => {
    if (_value && onChange) {
      onChange(`${_value.startOf("day").toISOString()}`);
    }
  }, [_value, onChange]);

  const applyButton = useCallback(
    () => (
      <Row justify="end">
        <Col>
          <Button size="small" type="primary" disabled={!_value} onClick={applyDate}>
            {t("label.apply")}
          </Button>
        </Col>
      </Row>
    ),
    [_value, applyDate, t]
  );

  return (
    <InlineDatePicker
      value={_value}
      showToday={false}
      onChange={doUpdate as AnyObject}
      renderExtraFooter={applyButton}
      className="ant-ext-sd__picker ant-ext-sd__picker--date"
    />
  );
})
Example #22
Source File: calendar-view.ts    From obsidian-dataview with MIT License 5 votes vote down vote up
async render() {
        this.container.innerHTML = "";
        let maybeResult = await asyncTryOrPropogate(() =>
            executeCalendar(this.query, this.index, this.origin, this.settings)
        );
        if (!maybeResult.successful) {
            renderErrorPre(this.container, "Dataview: " + maybeResult.error);
            return;
        } else if (maybeResult.value.data.length == 0 && this.settings.warnOnEmptyResult) {
            renderErrorPre(this.container, "Dataview: Query returned 0 results.");
            return;
        }
        let dateMap = new Map<string, CalendarFile[]>();
        for (let data of maybeResult.value.data) {
            const dot = {
                color: "default",
                className: "note",
                isFilled: true,
                link: data.link,
            };
            const d = data.date.toFormat("yyyyLLdd");
            if (!dateMap.has(d)) {
                dateMap.set(d, [dot]);
            } else {
                dateMap.get(d)?.push(dot);
            }
        }

        const querySource: ICalendarSource = {
            getDailyMetadata: async (date: Moment): Promise<IDayMetadata> => {
                return {
                    dots: dateMap.get(date.format("YYYYMMDD")) || [],
                };
            },
        };

        const sources: ICalendarSource[] = [querySource];
        const renderer = this;
        this.calendar = new Calendar({
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            target: (this as any).container,
            props: {
                onHoverDay(date: Moment, targetEl: EventTarget): void {
                    const vals = dateMap.get(date.format("YYYYMMDD"));
                    if (!vals || vals.length == 0) {
                        return;
                    }
                    if (vals?.length == 0) {
                        return;
                    }

                    renderer.app.workspace.trigger("link-hover", {}, targetEl, vals[0].link.path, vals[0].link.path);
                },
                onClickDay: async date => {
                    const vals = dateMap.get(date.format("YYYYMMDD"));
                    if (!vals || vals.length == 0) {
                        return;
                    }
                    if (vals?.length == 0) {
                        return;
                    }
                    const file = renderer.app.metadataCache.getFirstLinkpathDest(vals[0].link.path, "");
                    if (file == null) {
                        return;
                    }
                    const leaf = renderer.app.workspace.getUnpinnedLeaf();
                    await leaf.openFile(file, { active: true });
                },
                showWeekNums: false,
                sources,
            },
        });
    }
Example #23
Source File: index.tsx    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
DateRangeFilterItem = ({
  itemData,
  value,
  active,
  onVisibleChange,
  onChange,
  onQuickOperation,
  labels,
}: Merge<IFilterItemProps<'dateRange'>, { labels: JSX.Element }>) => {
  const { key, label, type, placeholder, disabled, required, customProps } = itemData;
  const [_startDate, _endDate] = value || [];
  const startDate = typeof _startDate === 'string' ? +_startDate : _startDate;
  const endDate = typeof _endDate === 'string' ? +_endDate : _endDate;
  const { borderTime } = customProps || {};

  const disabledDate = (isStart: boolean) => (current: Moment | undefined) => {
    return (
      !!current &&
      (isStart
        ? endDate
          ? (borderTime ? current.startOf('dates') : current) > moment(endDate)
          : false
        : startDate
        ? (borderTime ? current.endOf('dates') : current) < moment(startDate)
        : false)
    );
  };

  const getTimeValue = (v: any[]) => {
    if (borderTime) {
      const startVal = v[0]
        ? moment(isString(v[0]) ? +v[0] : v[0])
            .startOf('dates')
            .valueOf()
        : v[0];
      const endVal = v[1]
        ? moment(isString(v[1]) ? +v[1] : v[1])
            .endOf('dates')
            .valueOf()
        : v[1];
      return [startVal, endVal];
    }
    return v;
  };

  return (
    <span className="contractive-filter-item contractive-filter-date-picker">
      {labels}
      <DatePicker
        size="small"
        bordered={false}
        disabled={disabled}
        value={startDate ? moment(startDate) : undefined}
        disabledDate={disabledDate(true)}
        format={'YYYY/MM/DD'}
        allowClear={!required}
        onChange={(v) => onChange({ key, value: getTimeValue([v?.valueOf(), endDate]) })}
        placeholder={i18n.t('common:Start date')}
      />
      <span className="text-desc">{i18n.t('common:to')}</span>
      <DatePicker
        size="small"
        bordered={false}
        disabled={disabled}
        allowClear={!required}
        value={endDate ? moment(endDate) : undefined}
        disabledDate={disabledDate(false)}
        format={'YYYY/MM/DD'}
        placeholder={i18n.t('common:End date')}
        onChange={(v) => onChange({ key, value: getTimeValue([startDate, v?.valueOf()]) })}
      />
    </span>
  );
}
Example #24
Source File: moment-adapter.ts    From angular-material-components with MIT License 5 votes vote down vote up
getYear(date: Moment): number {
    return this.clone(date).year();
  }