如何在TypeScript中设置日期/时间的格式?

How do you format a Date/Time in TypeScript?

本文关键字:时间 格式 日期 设置 TypeScript      更新时间:2023-09-26

我一直有一些麻烦试图得到一个Date对象在TypeScript格式化我想要的方式。

我有一个类Module,定义为:

export class Module {
    constructor(public id: number, public name: string, public description: string, 
                 public lastUpdated: Date, public owner: string) { }
    getNiceLastUpdatedTime(): String {
        let options: Intl.DateTimeFormatOptions = {
            day: "numeric", month: "numeric", year: "numeric",
            hour: "2-digit", minute: "2-digit"
        };
        return this.lastUpdated.toLocaleDateString("en-GB", options) + " " + this.lastUpdated.toLocaleTimeString("en-GB", options);
    }
}

当我用以下代码调用方法时:

    let date = new Date(1478708162000); // 09/11/2016 16:16pm (GMT)
    let module = new Module(1, "Test", "description", date, "test owner");
    console.log(module.getNiceLastUpdatedTime());

我最终在控制台中打印了以下内容:

'9 November 2016 16:16:02 GMT'

我想看到的是:

09/11/2015 16:16

我已经看了一下文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString,我仍然看不出我做错了什么(我知道这是一个JavaScript API文档,但我很确定这是TypeScript在引子下使用的)。

如果您想要超时以及日期您想要Date.toLocaleString() .

这是直接从我的控制台:

> new Date().toLocaleString()
> "11/10/2016, 11:49:36 AM"

然后您可以输入区域设置字符串和格式化字符串以获得您想要的精确输出。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

选项1: Momentjs:

安装:

npm install moment --save
进口:

import * as moment from 'moment';

用法:

let formattedDate = (moment(yourDate)).format('DD-MMM-YYYY HH:mm:ss')

选项2:如果你在做Angular,使用DatePipe:

进口:

import { DatePipe } from '@angular/common';

用法:

const datepipe: DatePipe = new DatePipe('en-US')
let formattedDate = datepipe.transform(yourDate, 'dd-MMM-YYYY HH:mm:ss')

对于Angular,你应该简单地使用formatDate而不是DatePipe

import {formatDate} from '@angular/common';
constructor(@Inject(LOCALE_ID) private locale: string) { 
    this.dateString = formatDate(Date.now(),'yyyy-MM-dd',this.locale);
}

使用the Temporal API (2023)

一个新的js日期api在第三阶段的提案中(时间api)。请看一看,你可以用它在不久的将来解决你的大部分问题: https://tc39.es/proposal-temporal/docs/index.html

停止使用momentjs -参见下面的替代方法

正如@jonhF在评论中指出的,MomentJs建议不要再使用MomentJs了。检查https://momentjs.com/docs/

相反,我将这个列表与我个人的TOP 3 js日期库保存在一起,以备将来参考。

  • Date-fns - https://date-fns.org/
  • DayJS - https://day.js.org/
  • JS-Joda - https://js-joda.github.io/js-joda/
<标题>老评论

(不要再使用momentjs lib了,它已经被弃用了!!)

我建议你使用MomentJS

随着时间的推移,你可以有很多输出,这一个09/11/2015 16:16是其中之一。

  1. 你可以创建继承自PipeTransform基的管道
  2. 然后实现transform方法

在Angular 4中使用-它工作了。格式化日期的最佳方法是使用管道。

像这样创建您的自定义管道:

import { Pipe, PipeTransform} from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
    name: 'dateFormat'
  })
  export class DateFormatPipe extends DatePipe implements PipeTransform {
    transform(value: any, args?: any): any {
       ///MMM/dd/yyyy 
       return super.transform(value, "MMM/dd/yyyy");
    }
  }

,它在TypeScript类中是这样使用的:

////my class////
export class MyComponent
{
  constructor(private _dateFormatPipe:DateFormatPipe)
  {
  }
  formatHereDate()
  {
     let myDate = this._dateFormatPipe.transform(new Date())//formatting current ///date here 
     //you can pass any date type variable 
  }
}

如果你在angular中需要它,用最少的代码最简单的方法是:

import {formatDate} from '@angular/common';
formatDate(Date.now(),'yyyy-MM-dd','en-US');

这是Angular的另一个选项(使用自己的格式化函数)——这个是用于格式化的:

YYYY-mm-dd hh:神经网络:ss

-你可以调整你的格式,只是重新排列行和改变分隔符

dateAsYYYYMMDDHHNNSS(date): string {
  return date.getFullYear()
            + '-' + this.leftpad(date.getMonth() + 1, 2)
            + '-' + this.leftpad(date.getDate(), 2)
            + ' ' + this.leftpad(date.getHours(), 2)
            + ':' + this.leftpad(date.getMinutes(), 2)
            + ':' + this.leftpad(date.getSeconds(), 2);
}
leftpad(val, resultLength = 2, leftpadChar = '0'): string {
  return (String(leftpadChar).repeat(resultLength)
        + String(val)).slice(String(val).length);
}

当前时间戳使用如下:

const curTime = this.dateAsYYYYMMDDHHNNSS(new Date());
console.log(curTime);

将输出例如:2018-12-31 23:00:01

function _formatDatetime(date: Date, format: string) {
   const _padStart = (value: number): string => value.toString().padStart(2, '0');
return format
    .replace(/yyyy/g, _padStart(date.getFullYear()))
    .replace(/dd/g, _padStart(date.getDate()))
    .replace(/mm/g, _padStart(date.getMonth() + 1))
    .replace(/hh/g, _padStart(date.getHours()))
    .replace(/ii/g, _padStart(date.getMinutes()))
    .replace(/ss/g, _padStart(date.getSeconds()));
}
function isValidDate(d: Date): boolean {
    return !isNaN(d.getTime());
}
export function formatDate(date: any): string {
    var datetime = new Date(date);
    return isValidDate(datetime) ? _formatDatetime(datetime, 'yyyy-mm-dd hh:ii:ss') : '';
}

要添加@kamalakar的答案,需要在app.module中导入相同的内容,并将DateFormatPipe添加到providers中。

    import {DateFormatPipe} from './DateFormatPipe';
    @NgModule
    ({ declarations: [],  
        imports: [],
        providers: [DateFormatPipe]
    })

可以使用

function formatDate(date) { 
 return date.toISOString().replace('T', ' ').replaceAll('-', '/').substring(0, 19);
}
const currentdate = new Date();
console.log(formatDate(currentdate));

1º安装:npm install moment --save2 . Make Import: import moment, { Moment } from 'moment'3º编码器:

var date = Date.now()
let formattedDate = (moment(date)).format('YYYY-MM-DD HH:mm:ss')

这对我有用

    /**
     * Convert Date type to "YYYY/MM/DD" string 
     * - AKA ISO format?
     * - It's logical and sortable :)
     * - 20200227
     * @param Date eg. new Date()
     * https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd 
     * https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd?page=2&tab=active#tab-top
     */
    static DateToYYYYMMDD(Date: Date): string {
        let DS: string = Date.getFullYear()
            + '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
            + '/' + ('0' + Date.getDate()).slice(-2)
        return DS
    }

你当然可以像这样添加HH:MM…

    static DateToYYYYMMDD_HHMM(Date: Date): string {
        let DS: string = Date.getFullYear()
            + '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
            + '/' + ('0' + Date.getDate()).slice(-2)
            + ' ' + ('0' + Date.getHours()).slice(-2)
            + ':' + ('0' + Date.getMinutes()).slice(-2)
        return DS
    }

对我来说最好的解决方案是来自@Kamalakar的自定义管道,但稍加修改以允许传递格式:

import { Pipe, PipeTransform} from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
    name: 'dateFormat'
  })
  export class DateFormatPipe extends DatePipe implements PipeTransform {
    transform(value: any, format: any): any {
       return super.transform(value, format);
    }
  }

然后调用as:

console.log('Formatted date:', this._dateFormatPipe.transform(new Date(), 'MMM/dd/yyyy'));

下面是一个简单日期格式函数的示例

formatDate(value, format, offset){
 format = format || 'yyyy-MM-dd';
 offset = offset || '+0300';
if(!(value instanceof Date)){
   value = new Date(value);
   if(value === null || value === undefined) {
      throw new Error(
      'DateFormatException: value passed' + 'is not a valid date'
      );
    }
  }
  return value; // TODO implement this return $filter('date')(value, format, offset);
}