在TypeScript中格式化日期/时间

Mat*_*son 39 javascript typescript

我一直在尝试使用DateTypeScript中的对象来格式化我想要的方式.

我有一个类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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

    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());
Run Code Online (Sandbox Code Playgroud)

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

'9 November 2016 16:16:02 GMT'
Run Code Online (Sandbox Code Playgroud)

我想看到的是:

09/11/2015 16:16
Run Code Online (Sandbox Code Playgroud)

我看过以下文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString 我仍然无法看到我在做什么错(我知道这是一个JavaScript API文档,但我很确定这是TypeScript在幕后使用的).

dou*_*ald 43

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

这直接来自我的控制台:

> new Date().toLocaleString()
> "11/10/2016, 11:49:36 AM"
Run Code Online (Sandbox Code Playgroud)

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

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

  • 我的控制台的输出是一样的。然而,当我在 TypeScript 中使用相同的代码时,我得到的结果与我原来的帖子相同。 (2认同)

WtF*_*dgE 25

选项 1: Momentjs:

安装:

npm install moment --save
Run Code Online (Sandbox Code Playgroud)

进口:

import * as moment from 'moment';
Run Code Online (Sandbox Code Playgroud)

用法:

let formattedDate = (moment(yourDate)).format('DD-MMM-YYYY HH:mm:ss')
Run Code Online (Sandbox Code Playgroud)

选项 2:如果您正在使用 Angular,请使用 DatePipe:

进口:

import { DatePipe } from '@angular/common';
Run Code Online (Sandbox Code Playgroud)

用法:

const datepipe: DatePipe = new DatePipe('en-US')
let formattedDate = datepipe.transform(yourDate, 'DD-MMM-YYYY HH:mm:ss')
Run Code Online (Sandbox Code Playgroud)

  • Moment.js 是一个遗留项目,现在处于维护模式。可能应该使用其他东西 (2认同)
  • 对于 Angular,您不应该使用 DatePipe。请查看我的答案/sf/answers/4473167681/ (2认同)
  • 对于第二个选项,使用“dd-..”而不是“DD” (2认同)

gdr*_*drt 20

如果您需要它的角度,最简单的方法和最少的代码是:

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

formatDate(Date.now(),'yyyy-MM-dd','en-US');
Run Code Online (Sandbox Code Playgroud)


See*_*ega 14

对于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);
}
Run Code Online (Sandbox Code Playgroud)

  • 这对我来说非常有用,除了我已经使用的之外,我不需要使用任何额外的导入。formatDate 具有很好的灵活性,因为您可以传入日期、字符串或数字。另外,如果您不想注入 LACALE_ID 并使用 this.locale,您可以使用像 'en_US' 这样的简单字符串 (3认同)

小智 11

  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");
    }
  }
Run Code Online (Sandbox Code Playgroud)

它在像这样的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 
  }
}
Run Code Online (Sandbox Code Playgroud)


Fel*_*lix 11

Here is another option for Angular (using own formatting function) - this one is for format:

YYYY-mm-dd hh:nn:ss

-you can adjust to your formats, just re-order the lines and change separators

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);
}
Run Code Online (Sandbox Code Playgroud)

For current time stamp use like this:

const curTime = this.dateAsYYYYMMDDHHNNSS(new Date());
console.log(curTime);
Run Code Online (Sandbox Code Playgroud)

Will output e.g: 2018-12-31 23:00:01


Ren*_*ges 6

我建议您使用MomentJS

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

  • 2020 更新:Moment 现在建议不要使用 Moment。简而言之,本机日期格式支持已经变得更好,如果您仍然需要更多,可以使用更小、更好的库。查看他们的文档:https://momentjs.com/docs/ (3认同)

An *_*yen 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') : '';
}
Run Code Online (Sandbox Code Playgroud)