当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript date-fns.format函数代码示例

本文整理汇总了TypeScript中date-fns.format函数的典型用法代码示例。如果您正苦于以下问题:TypeScript format函数的具体用法?TypeScript format怎么用?TypeScript format使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了format函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1:

      _.each(groupedByDate, (dateGroup: any[]) => {

        const startDateValue = dateFunctions[`startOf${dateGroupBy}`](dateGroup[0][DATE_KEY]);
        const endDateValue = dateFunctions[`endOf${dateGroupBy}`](dateGroup[0][DATE_KEY]);

        _.each([startDateValue, endDateValue], date => {
          dateFunctions.setSeconds(date, 0);
          dateFunctions.setMinutes(date, 0);
        });

        const startDateFormatted = dateFunctions.format(startDateValue, 'YYYY-MM-DD hh:mm A');
        const endDateFormatted = dateFunctions.format(endDateValue, 'YYYY-MM-DD hh:mm A');

        const baseObj = {
          'Purchase Time': `${startDateFormatted} - ${endDateFormatted}`,
          'Purchase Method': 'Unknown'
        };

        _.each(AGGREGATE_KEYS, aggKey => baseObj[aggKey.key] = 0);

        const aggregateObject = _.reduce(dateGroup, (prev, cur) => {
          _.each(AGGREGATE_KEYS, aggKey => prev[aggKey.key] += (+cur[aggKey.key] || 0));
          return prev;
        }, baseObj);

        _.each(AGGREGATE_KEYS, aggKey => aggregateObject[aggKey.key] = aggregateObject[aggKey.key].toFixed(aggKey.decimals));

        dataGroups[key].push(aggregateObject);
      });
开发者ID:Linko91,项目名称:posys,代码行数:29,代码来源:reportdatatransformer.ts

示例2: format

export const lastModifiedString = (date: string): string => {
  if (isToday(date)) {
    return format(date, "[Today at] H:mm a");
  } else if (differenceInCalendarISOWeeks(date, new Date()) >= -1) {
    return format(date, "dddd");
  }
  return format(date, "MMM D");
};
开发者ID:carlospaelinck,项目名称:publications-js,代码行数:8,代码来源:string.ts

示例3: convertDate

	convertDate(date: string, omitSeconds: boolean = false, dateFormat?: string) {
		if (dateFormat) { return format(new Date(date), dateFormat); }

		if (!omitSeconds) {
			return format(new Date(date), "MMM DD, YYYY HH:mm:ss");
		} else {
			return format(new Date(date), "MMM DD, YYYY HH:mm");
		}
	}
开发者ID:RinMinase,项目名称:anidb,代码行数:9,代码来源:utility.service.ts

示例4: create

	private async create(url: string, size: string, options: Options): Promise<Screenshot> {
		const basename = path.isAbsolute(url) ? path.basename(url) : url;

		let hash = parseUrl(url).hash || '';
		// Strip empty hash fragments: `#` `#/` `#!/`
		if (/^#!?\/?$/.test(hash)) {
			hash = '';
		}

		const [width, height] = size.split('x');

		const filenameTemplate = template(`${options.filename}.${options.format}`);

		const now = Date.now();
		let filename = filenameTemplate({
			crop: options.crop ? '-cropped' : '',
			date: dateFns.format(now, 'YYYY-MM-DD'),
			time: dateFns.format(now, 'HH-mm-ss'),
			size,
			width,
			height,
			url: `${filenamifyUrl(basename)}${filenamify(hash)}`
		});

		if (options.incrementalName) {
			filename = unusedFilename.sync(filename);
		}

		// TODO: Type this using the `capture-website` types
		const finalOptions: any = {
			width: Number(width),
			height: Number(height),
			delay: options.delay,
			timeout: options.timeout,
			fullPage: !options.crop,
			styles: options.css && [options.css],
			scripts: options.script && [options.script],
			cookies: options.cookies, // TODO: Support string cookies in capture-website
			element: options.selector,
			hideElements: options.hide,
			scaleFactor: options.scale === undefined ? 1 : options.scale,
			type: options.format === 'jpg' ? 'jpeg' : 'png',
			userAgent: options.userAgent,
			headers: options.headers
		};

		if (options.username && options.password) {
			finalOptions.authentication = {
				username: options.username,
				password: options.password
			};
		}

		const screenshot = await captureWebsite.buffer(url, finalOptions) as any;
		screenshot.filename = filename;
		return screenshot;
	}
开发者ID:sindresorhus,项目名称:pageres,代码行数:57,代码来源:index.ts

示例5: autofillYear

	autofillYear(date: string) {
		if (date.split(" ").length === 2) {
			const monthRaw: any = parseInt(date.split(" ")[0]) || date.split(" ")[0];
			const day = date.split(" ")[1];
			let month: any;

			month = (isNaN(monthRaw)) ? this.getMonthByName(monthRaw) : format(parse(monthRaw), "MM");

			const yearToday = getYear(new Date());
			const dateParsed = `${month}-${day}-${yearToday}`;
			const dateParsedUnix = this.getUnix(parse(dateParsed));
			const dateTodayUnix = this.getUnix();

			if (dateParsedUnix > dateTodayUnix) {
				date += ` ${(yearToday - 1).toString()}`;
			} else {
				date += ` ${yearToday.toString()}`;
			}
		}

		if ((new Date(date)).toString().indexOf("Invalid Date") === 0) {
			return this.getUnix();
		} else {
			return this.getUnix(new Date(date));
		}
	}
开发者ID:RinMinase,项目名称:anidb,代码行数:26,代码来源:utility.service.ts

示例6: formatTime

export function formatTime(time: string | number): string {
  const timeNumber = typeof time === 'string' ? parseInt(time, 10) : time;

  if (timeNumber === 0) return '12 midnight';
  if (timeNumber === 1200) return '12 noon';

  return format(getTimeAsDate(timeNumber), 'h:mm a').toLowerCase();
}
开发者ID:nusmodifications,项目名称:nusmods,代码行数:8,代码来源:timify.ts

示例7: Promise

  return new Promise(resolve => {
    const notes = path.resolve(__dirname, `../src/notes/${topic}`)
    const note = path.join(notes, `${dateFns.format(date, 'yyyy-MM-dd')}--${padStart(String(count), 2, '0')}`)

    fs.access(note, fs.constants.F_OK, async err => {
      if (err) return resolve(note)
      return resolve(await uniqueNote(topic, date, count + 1))
    })
  })
开发者ID:jeremyboles,项目名称:jeremyboles.com,代码行数:9,代码来源:import.ts

示例8: test

test('`filename` option', async t => {
	const screenshots = await new Pageres()
		.src(server.url, ['1024x768'], {
			filename: '<%= date %> - <%= time %> - <%= url %>'
		})
		.run();

	t.is(screenshots.length, 1);
	t.regex(screenshots[0].filename, new RegExp(`${dateFns.format(Date.now(), 'YYYY-MM-DD')} - \\d{2}-\\d{2}-\\d{2} - ${server.host}!${server.port}.png`));
});
开发者ID:sindresorhus,项目名称:pageres,代码行数:10,代码来源:test.ts

示例9: async

  async(inject([MatDialog, MatDialogRef], (dialogSpy: MatDialog, dialogRef: MatDialogRef<any>) => {
    const now = new Date();
    const startTime = format(getTime(startOfMinute(now)), 'HH:mm');
    const endTime = format(getTime(addHours(startOfMinute(now), 1)), 'HH:mm');
    const lesson: Lesson = {
      id: 0,
      date: now,
      startTime: startTime,
      endTime: endTime,
      lessonAttendees: [],
      status: 'active'
    };

    component.addLesson(now);
    expect(dialogSpy.open).toHaveBeenCalledWith(LessonEditorComponent, {
      autoFocus: false,
      data: lesson
    });
    dialogRef.afterClosed().subscribe((result) => expect(result).toBeTruthy());
    dialogRef.close(lesson);
  })));
开发者ID:vgebrev,项目名称:Tesli,代码行数:21,代码来源:calendar.component.spec.ts

示例10: inject

  inject([LessonService], (lessonService) => {
    const calendarEvent = component.events[0];
    const newStart =  parse(format(new Date(), 'YYYY-MM-DD'));
    const newEnd = addHours(newStart, 1);
    let refreshed = false;

    component.refresh.subscribe(() => refreshed = true);
    component.changeEventTimes({ event: calendarEvent, newStart: newStart, newEnd: newEnd, type: undefined });

    expect(calendarEvent.start).toEqual(newStart);
    expect(calendarEvent.end).toEqual(newEnd);
    expect(refreshed).toBeTruthy();
    expect(lessonService.updateLesson).toHaveBeenCalledWith(calendarEvent.meta);
  }));
开发者ID:vgebrev,项目名称:Tesli,代码行数:14,代码来源:calendar.component.spec.ts

示例11: entry

async function entry(options: Options) {
  if (!options.title) {
    console.error('No title given!')
    process.exit(1)
    return
  }

  if (!options.topic) {
    console.error('No topic given!')
    process.exit(1)
    return
  }

  if (!(await topicExists(options.topic))) {
    console.error(`The topic "${options.topic}" does not exists`)
    process.exit(1)
    return
  }

  const date = new Date()

  const dir = path.resolve(
    __dirname,
    `../src/entries/${options.topic}/${dateFns.format(date, 'yyyy-MM-dd')}-${makeSlug(options.title, '-')}`
  )
  try {
    await fs.promises.access(dir, fs.constants.F_OK)
    console.error(`A entry already named '${options.title}' already exists for today`)
    return
  } catch (error) {
    const publishedAt = date.toISOString()
    const text = '_Content goes here_'
    const mdx = `---\ntitle: ${
      options.title
    }\npublishedAt: ${publishedAt}\n\ncover:\n  image: full.jpg\n  caption: Starter caption.\n---\n\n${text}\n`

    await fs.promises.mkdir(dir, { recursive: true })

    const file = `${dir}/index.mdx`
    await fs.promises.writeFile(file, mdx)

    console.log(`Created a new entry: ${file.replace(path.resolve(__dirname, '..'), '')}`)
  }
}
开发者ID:jeremyboles,项目名称:jeremyboles.com,代码行数:44,代码来源:make.ts

示例12: timeOutAuthAttempts

    private async timeOutAuthAttempts(timer: boolean = false): Promise<boolean> {
        const findByRules = {
            ip: address(),
            timestamp: null
        };

        // Just in case if we need to check by timestamp
        if (timer) {
            findByRules.timestamp = LessThan(format(subMinutes(new Date(), 5), 'YYYY-MM-DD HH:mm:ss'));
        }

        // Fetching attempts
        const response = await getConnection().getRepository(MoUsersAuthAttempts).find(findByRules);

        // Cleaning up outdated attempts
        if (response) {
            await getConnection().getRepository(MoUsersAuthAttempts).remove(response);
        }

        return true;
    }
开发者ID:Maxtream,项目名称:themages-cms,代码行数:21,代码来源:login.ts

示例13: split

 const stream = split((json: string): string => {
   try {
     const parsed = new Parse(json);
     const logObj: LogObject = parsed.value;
     if (parsed.err) {
       return json + EOL;
     }
     if (!debug && logObj.level <= 20) {
       return '';
     }
     const dateString = formatDate(new Date(logObj.time), dateFormat);
     const levelString = levelColors[logObj.level](levels[logObj.level]);
     const labelString = withLabel ? `[${logObj.label}] ` : '';
     return `${dateString} ${levelString} ${labelString}${logObj.msg}${EOL}`;
   } catch (ex) {
     if (ex && ex.message) {
       console.log(ex.message);
     }
     return '';
   }
 });
开发者ID:HarryTmetic,项目名称:r2,代码行数:21,代码来源:pretty.ts

示例14: distanceInWordsStrict

      .subscribe(data => {
        if (data) {
          if (!_.isEqual(this.previousRecentErrors, data.recent_errors)) {
            this.previousRecentErrors = _.cloneDeep(data.recent_errors);
            this.recentErrors = data.recent_errors;
          }

          this.chartValue = {count: data.average_response_time_sec, date: data.time};
          this.statusCodeValue = Object.keys(data.total_status_code_count)
            .map(key => ({code: key, count: data.total_status_code_count[key]}));

          this.pid = data.pid;
          this.uptime = distanceInWordsStrict(subSeconds(new Date(), data.uptime_sec), new Date());
          this.uptimeSince = format(subSeconds(new Date(), data.uptime_sec), 'YYYY-MM-DD HH:mm:ss Z');
          this.totalResponseTime = distanceInWordsStrict(subSeconds(new Date(), data.total_response_time_sec), new Date());
          this.exactTotalResponseTime = data.total_response_time;
          this.averageResponseTime = Math.floor(data.average_response_time_sec * 1000) + ' ms';
          this.exactAverageResponseTime = data.average_response_time;
          this.codeCount = data.count;
          this.totalCodeCount = data.total_count;
        }
      });
开发者ID:marc-j,项目名称:traefik,代码行数:22,代码来源:health.component.ts

示例15: Date

    return _.reduce(report.columns, (prev, cur: any) => {
      if(!cur.checked && !cur.always) { return prev; }
      const value = _.get(item, cur.key, '');

      prev[cur.name] = value;

      if(_.isNull(value)) {
        prev[cur.name] = '';
      }

      if(_.includes(['Purchase Time', 'Last Sold', 'Start Date', 'End Date'], cur.name)) {
        if(!value) {
          prev[cur.name] = 'Never';
        } else {
          prev[cur.name] = dateFunctions.format(new Date(value), 'YYYY-MM-DD hh:mm A');
        }
      }

      if(cur.name === 'Purchase Method') {
        prev[cur.name] = settings.invoiceMethodDisplay(value);
      }

      return prev;
    }, {});
开发者ID:Linko91,项目名称:posys,代码行数:24,代码来源:reportdatatransformer.ts


注:本文中的date-fns.format函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。