如何在TypeScript中格式化日期/时间?


70

我一直在尝试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在后台使用的内容)。


1
Date的格式不是TypeScript可以影响的,而只是javascript。
Alex

@Alex,即使TypeScripttoLocale...函数将接受语言环境和选项对象,它们实际上也没有用?
马特·沃森

1
没有像这样的TypeScript函数,即javascript函数。TypeScript只知道api并为其提供类型化的接口。
亚历克斯

我现在知道了 看了一下转译后的代码,它直接将其直接传递给未修改的对象。看来问题出在PhantomJS及其实现Date API的方式上。它的格式在外观上与其他浏览器不同。在Chrome中运行它可以提供预期的输出。
马特·沃森

Answers:


70

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

这直接来自我的控制台:

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

然后,您可以输入区域设置字符串和格式字符串以获取所需的精确输出。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString


2
我的控制台的输出是相同的。但是,当我在TypeScript中使用相同的代码时,得到的结果与原始帖子相同。
马特·沃森

看来问题出在PhantomJS及其实现Date API的方式上。它的格式在外观上与其他浏览器不同。在Chrome中运行它可以提供预期的输出。
马特·沃森

不要让我开始使用Phantom!原理上很棒,生气时总是有像这样的有趣的错误!
dougajmcdonald '16

15
  1. 您可以创建从PipeTransform基础继承的管道
  2. 然后实现变换方法

在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 
  }
}

11

这是Angular的另一个选项(使用自己的格式化功能)-这个是用于格式化的:

YYYY-mm-dd hh:nn: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


9

更新(2020)

正如@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

现在,您可以有很多输出,而这09/11/2015 16:16就是其中之一。


2020年更新:Moment现在建议不要使用Moment。简短的解释是,本机日期格式支持已变得更好,并且如果您仍然需要更多,则可以使用更小更好的库。参见他们的文档:momentjs.com/docs
JohnF,

6

选项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')

我认为最好的答案。我不知道我们可以在组件中使用DatePipe。Thx bro
FelipeThomé20年

Moment.js是一个旧项目,现在处于维护模式。也许应该使用别的东西👌
哈利林肯

5
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') : '';
}

1
为我工作。谢谢!
jade290

1

对于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);
}

0

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

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

-1

这对我有用

    /**
     * Convert Date type to "YYYY/MM/DD" string 
     * - AKA ISO format?
     * - It's logical and sortable :)
     * - 20200227
     * @param Date eg. new Date()
     * /programming/23593052/format-javascript-date-as-yyyy-mm-dd 
     * /programming/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
    }

-2

对我来说最好的解决方案是来自@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);
    }
  }

然后称为:

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

-24

我有一个类似的问题,我解决了

.format();

1
您是如何解决这个问题的?您是否有显示输入和结果的完整代码段?
比利·威洛比

我猜该解决方案有效,因为您使用的是矩依赖或类似的方法,但是此答案不正确,因为您未指定来源是.format()
gon250 '19
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.