• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: format

 return feed.items.splice(0, 5).map((item: any) => ({
   title: item.title,
   url: item.link,
   date: format(item.isoDate, "DD.MM.YYYY"),
 }));
开发者ID:drublic,项目名称:vc,代码行数:5,代码来源:getWdPosts.ts


示例17: formatDate

 formatDate(date: string): string {
     // formats like 22/10/
     // docs
     // https://date-fns.org/v1.29.0/docs/format
     return JSON.stringify(format(date, 'DD/MM/YYYY'));
 }
开发者ID:asadsahi,项目名称:AspNetCoreSpa,代码行数:6,代码来源:field-base.ts


示例18: format

 format(date: Date, format: string): string {
   return dateFnsFormat(date, format);
 }
开发者ID:ng-lightning,项目名称:ng-lightning,代码行数:3,代码来源:date-fns-adapter.ts


示例19: format

export const dateFormat = (date: DateType, f: string = 'yyyy-MM-dd') =>
  format(typeof date === 'string' ? parseISO(date) : date, f)
开发者ID:JounQin,项目名称:blog,代码行数:2,代码来源:time.ts


示例20: Date

      const printInvoice = (invoice: InvoiceModel, copy = 'Merchant') => {

        thermalPrinter.clear();
        thermalPrinter.init({ width: characterWidth, type });

        thermalPrinter.openCashDrawer();

        if(businessName) {
          thermalPrinter.alignCenter();
          thermalPrinter.setTextDoubleHeight();
          thermalPrinter.println(businessName);
          thermalPrinter.setTextNormal();
          thermalPrinter.alignLeft();
        }

        if(header) {
          thermalPrinter.alignCenter();
          thermalPrinter.println(header);
          thermalPrinter.newLine();
          thermalPrinter.alignLeft();
        }

        thermalPrinter.leftRight('Method', invoice.purchaseMethod);
        thermalPrinter.leftRight('Time', dateFunctions.format(new Date(invoice.purchaseTime), 'YYYY-MM-DD hh:mm A'));
        thermalPrinter.leftRight('Location', invoice.location.name);
        thermalPrinter.leftRight('Terminal', invoice.terminalId);
        thermalPrinter.leftRight('# Items', _.sumBy(invoice.stockitems, 'quantity'));
        thermalPrinter.newLine();

        _.each(invoice.stockitems, item => {
          thermalPrinter.alignLeft();

          // space for up to 100$ worth in transaction before the stuff starts to overlap
          const rightSideSpace = 8;
          const skuHalf = `-${item.realData.sku}`;
          const nameLength = characterWidth - skuHalf.length - rightSideSpace;
          const cleanedName = cleanName(item.realData.name, nameLength);
          thermalPrinter.println(`${cleanedName}${skuHalf}`);
          thermalPrinter.leftRight(`${item.quantity} x ${item.cost}`, (+(item.cost * item.quantity)).toFixed(2));

          _.each(invoice.promotions, promo => {
            if(item.promoApplyId !== promo.applyId) {
              return;
            }

            thermalPrinter.leftRight(cleanName(promo.realData.name, characterWidth - rightSideSpace), promo.cost);
          });
        });

        thermalPrinter.newLine();

        thermalPrinter.leftRight('Subtotal', invoice.subtotal);
        thermalPrinter.leftRight('Tax', invoice.taxCollected);

        thermalPrinter.setTextDoubleHeight();
        thermalPrinter.leftRight('Grand Total', invoice.purchasePrice);
        thermalPrinter.setTextNormal();

        if(invoice.purchaseMethod === 'Cash') {
          thermalPrinter.leftRight('Cash Given', invoice.cashGiven);
          thermalPrinter.leftRight('Change', invoice.cashGiven - invoice.purchasePrice);
        }

        thermalPrinter.newLine();

        thermalPrinter.newLine();

        if(footer) {
          thermalPrinter.alignCenter();
          thermalPrinter.println(footer);
        }

        thermalPrinter.newLine();
        thermalPrinter.alignCenter();
        thermalPrinter.println(`${copy} Copy`);
        thermalPrinter.newLine();

        thermalPrinter.alignCenter();
        if(printReceiptBarcodes) {
          if(type === 'epson') {
            thermalPrinter.printBarcode(invoice.id, { });
          } else if(type === 'star') {
            thermalPrinter.code128(invoice.id, { width: 'MEDIUM', text: 1 });
          }
        }
        thermalPrinter.newLine();
        thermalPrinter.println(`Invoice #${invoice.id}`);
        thermalPrinter.alignLeft();

        thermalPrinter.cut();
      };
开发者ID:Linko91,项目名称:posys,代码行数:91,代码来源:invoice.ts



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript date-fns.isBefore函数代码示例发布时间:2022-05-25
下一篇:
TypeScript date-fns.endOfDay函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap