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

我一直有一些麻烦,试图得到一个 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 正在暗中使用它)。

531218 次浏览

更新(2022年)

一个新的 js 日期 API 在第3阶段提案(时态 API)中。请看看这个,你也许可以在不久的将来用它解决你的大部分问题:

Https://tc39.es/proposal-temporal/docs/index.html

更新(2020年)

正如@jonhF 在评论中指出的那样,MomentJs 建议不要再使用 MomentJs 了。 检查“ a href = “ https://Momentjs.com/docs/”rel = “ norefrer”> https://momentjs.com/docs/

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

老话了

(不要再使用 Momentjs lib 了,它已经过时了! ! !)

我建议你使用 等一下

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

如果你想要的时间以及日期,你想 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. 您可以创建从 PipeTransform 基继承的管道
  2. 然后实现转换方法

用于角度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");
}
}

它用在类型脚本类中,如下所示:

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

要添加@kamalakar 的答案,还需要在 app.module 中导入相同的命令,并向提供程序添加 DateFormatPipe。

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

下面是 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-3123: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') : '';
}

这招对我很管用

    /**
* 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);
}
}

然后叫做:

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

选项1: 瞬间:

安装:

npm install moment --save

进口:

import * as moment from 'moment';

用法:

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

选项2: 使用日期管如果你使用角度:

进口:

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

用法:

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

对于 角度,您应该简单地使用 formatDate而不是 DatePipe

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


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

如果你需要它的角度,最简单的方法与最小代码是:

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


formatDate(Date.now(),'yyyy-MM-dd','en-US');

你可以用

function formatDate(date) {
return date.toISOString().replace('T', ' ').replaceAll('-', '/').substring(0, 19);
}


const currentdate = new Date();


console.log(formatDate(currentdate));

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

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