programing

TypeScript에서 날짜/시간을 포맷하려면 어떻게 해야 합니까?

cafebook 2023. 3. 19. 18:28
반응형

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가 후드 아래에서 사용하고 있는 것은 확실합니다).

원하는 날짜뿐만 아니라 타임아웃을 원하는 경우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: 모멘트:

인스톨:

npm install moment --save

Import:

import * as moment from 'moment';

사용방법:

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

옵션 2: Angular를 사용하는 경우 DatePipe 사용:

Import:

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

Temporal API 사용(2023)

새로운 js date api는 3단계 제안(Temporal API)에 있습니다.이것을 봐 주세요.조만간 대부분의 문제를 해결할 수 있을지도 모릅니다.

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

momentj 사용을 중지합니다.아래의 대체 방법을 참조해 주세요.

댓글에서 @jonhF가 지적한 바와 같이 MomentJs는 더 이상 MomentJs를 사용하지 않을 것을 권장합니다.https://momentjs.com/docs/ 를 확인해 주세요.

대신, 저는 나중에 참조할 수 있도록 이 목록을 개인 TOP 3 js 날짜 라이브러리와 함께 보관하고 있습니다.

오래된 코멘트

(momentjs lib는 더 이상 사용하지 않습니다!!!)

모멘트를 사용하는 것이 좋습니다.JS

모멘트가 있으면 많은 출력을 얻을 수 있습니다.09/11/2015 16:16그 중 하나입니다.

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

각도에 필요한 경우 최소 코드를 가진 가장 간단한 어프로치는 다음과 같습니다.

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

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

다음은 Angular(자체 형식 지정 기능 사용)에 대한 다른 옵션입니다. 이 옵션은 형식용입니다.

YYY-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

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에서 동일한 내용을 Import하고 DateFormatPipe를 공급자에 추가해야 합니다.

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

다음은 간단한 날짜 형식 함수의 예입니다.

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

1 †치:npm install moment --save Import : 2 § Import :import moment, { Moment } from 'moment' Coder 3 µ 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);
    }
  }

그 다음, 다음과 같이 호출합니다.

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

언급URL : https://stackoverflow.com/questions/40526102/how-do-you-format-a-date-time-in-typescript

반응형