Programing

NodeJS를 사용하여 UTC 날짜를 YYYY-MM-DD hh : mm : ss 문자열로 포맷하는 방법은 무엇입니까?

lottogame 2020. 5. 1. 07:58
반응형

NodeJS를 사용하여 UTC 날짜를 YYYY-MM-DD hh : mm : ss 문자열로 포맷하는 방법은 무엇입니까?


NodeJS를 사용하여 a Date를 다음 문자열 형식으로 형식화하려고 합니다.

var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");

어떻게해야합니까?


Node.js를 사용하는 경우 EcmaScript 5가 있어야하므로 Date에는 toISOString방법이 있습니다. ISO8601의 약간의 수정을 요청합니다.

new Date().toISOString()
> '2012-11-04T14:51:06.157Z'

몇 가지만 잘라 내면 설정됩니다.

new Date().toISOString().
  replace(/T/, ' ').      // replace T with a space
  replace(/\..+/, '')     // delete the dot and everything after
> '2012-11-04 14:55:45'

또는 한 줄로 : new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')

ISO8601은 반드시 UTC (첫 번째 결과에서 후행 Z로 표시됨)이므로 기본적으로 UTC를 얻습니다 (항상 좋은 것임).


업데이트 2017-03-29 : 날짜 -fn 추가, Moment 및 Datejs에 대한 참고 사항
업데이트 2016-09-14 : 일부 날짜 / 시간 기능이 우수한 것으로 보이는 SugarJS 추가


아무도 실제로 실제 답변을 제공하지 않았으므로 여기에 내 것이 있습니다.

라이브러리는 날짜와 시간을 표준 방식으로 처리하기에 가장 좋은 방법입니다. 날짜 / 시간 계산에는 많은 경우가 있으므로 개발을 라이브러리로 전달하는 것이 유용합니다.

기본 노드 호환 시간 형식 라이브러리 목록은 다음과 같습니다.

  • Moment.js [ Mustafa 덕분에 ] "날짜 구문 분석, 조작 및 형식화를위한 경량 (4.3k) 자바 스크립트 날짜 라이브러리"-국제화, 계산 및 상대 날짜 형식 포함- 업데이트 2017-03-29 : 매우 가벼운 무게 특히 시간대 지원이 필요한 경우 더 포괄적이지만 여전히 가장 포괄적 인 솔루션입니다.
  • date-fns [ Fractalf 덕분에 2017-03-29 추가 ] 작고 빠르며 표준 JS 날짜 객체와 작동합니다. 시간대 지원이 필요하지 않은 경우 Moment의 훌륭한 대안입니다.
  • SugarJS -JavaScript 내장 객체 유형에 필요한 기능을 추가하는 일반적인 도우미 라이브러리입니다. 뛰어난 날짜 / 시간 기능이 포함되어 있습니다.
  • strftime- 멋지고 간단하게 말하는 것
  • dateutil- 이것은 MomentJS 이전에 사용했던 것입니다
  • 노드 형식
  • TimeTraveller- "Time Traveler는 날짜를 처리하기위한 유틸리티 메소드 세트를 제공합니다. 추가 및 빼기에서 형식화에 이르기까지 Time Traveler는 글로벌 네임 스페이스를 오염시키지 않고 작성된 날짜 오브젝트 만 확장합니다."
  • Tempus [Dan 덕분에 감사]-업데이트 : Node와 함께 사용하고 npm과 함께 배포 할 수도 있습니다. 문서를 참조하십시오.

비 노드 라이브러리도 있습니다 :

  • Datejs [Peter Olson에게 감사] -npm 또는 GitHub에 패키지되어 있지 않으므로 Node에서 사용하기가 쉽지 않습니다. 2007 년 이후로 업데이트되지 않았으므로 권장되지 않습니다!

변환을위한 라이브러리가 있습니다 :

npm install dateformat

그런 다음 요구 사항을 작성하십시오.

var dateFormat = require('dateformat');

그런 다음 값을 바인딩하십시오.

var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");

dateformat 참조


나는 도서관에 대해 일반적으로 아무것도 없다. 이 경우, 응용 프로그램 프로세스의 다른 부분이 많이 날짜가되지 않는 한 범용 라이브러리는 과도하게 보입니다.

이와 같은 작은 유틸리티 기능을 작성하는 것은 초보자와 숙련 된 프로그래머 모두에게 유용한 연습이며 초보자들에게는 학습 경험이 될 수 있습니다.

function dateFormat (date, fstr, utc) {
  utc = utc ? 'getUTC' : 'get';
  return fstr.replace (/%[YmdHMS]/g, function (m) {
    switch (m) {
    case '%Y': return date[utc + 'FullYear'] (); // no leading zeros required
    case '%m': m = 1 + date[utc + 'Month'] (); break;
    case '%d': m = date[utc + 'Date'] (); break;
    case '%H': m = date[utc + 'Hours'] (); break;
    case '%M': m = date[utc + 'Minutes'] (); break;
    case '%S': m = date[utc + 'Seconds'] (); break;
    default: return m.slice (1); // unknown code, remove %
    }
    // add leading zero if required
    return ('0' + m).slice (-2);
  });
}

/* dateFormat (new Date (), "%Y-%m-%d %H:%M:%S", true) returns 
   "2012-05-18 05:37:21"  */

라이브러리를 사용하지 않고도 원하는 형식으로 타임 스탬프를 쉽게 읽을 수 있고 사용자 정의 할 수있는 방법 :

function timestamp(){
  function pad(n) {return n<10 ? "0"+n : n}
  d=new Date()
  dash="-"
  colon=":"
  return d.getFullYear()+dash+
  pad(d.getMonth()+1)+dash+
  pad(d.getDate())+" "+
  pad(d.getHours())+colon+
  pad(d.getMinutes())+colon+
  pad(d.getSeconds())
}

(UTC 형식의 시간이 필요한 경우 함수 호출 만 변경하십시오. 예를 들어 "getMonth"는 "getUTCMonth"가됩니다)


자바 스크립트 라이브러리 sugar.js ( http://sugarjs.com/ )에는 날짜 형식을 지정하는 기능이 있습니다.

예:

Date.create().format('{dd}/{MM}/{yyyy} {hh}:{mm}:{ss}.{fff}')

Date 객체에 제공된 방법을 다음과 같이 사용하십시오.

var ts_hms = new Date();

console.log(
    ts_hms.getFullYear() + '-' + 
    ("0" + (ts_hms.getMonth() + 1)).slice(-2) + '-' + 
    ("0" + (ts_hms.getDate())).slice(-2) + ' ' +
    ("0" + ts_hms.getHours()).slice(-2) + ':' +
    ("0" + ts_hms.getMinutes()).slice(-2) + ':' +
    ("0" + ts_hms.getSeconds()).slice(-2));

정말 더러워 보이지만 JavaScript 핵심 메소드에서 잘 작동합니다.


new Date(2015,1,3,15,30).toLocaleString()

//=> 2015-02-03 15:30:00

new Date().toString("yyyyMMddHHmmss").
      replace(/T/, ' ').  
      replace(/\..+/, '') 

toString ()을 사용하면 형식이됩니다.

바꾸기 (/ T /, ''). // T를 ''2017-01-15T로 바꿉니다 ...

replace (/..+/, '') // for ... 13 : 50 : 16.1271

예를 들어 var datehour:

var date="2017-01-15T13:50:16.1271".toString("yyyyMMddHHmmss").
                    replace(/T/, ' ').      
                    replace(/\..+/, '');
    
                    var auxCopia=date.split(" ");
                    date=auxCopia[0];
                    var hour=auxCopia[1];

console.log(date);
console.log(hour);


Nodejs와 angularjs에서 dateformat사용 하고 있습니다.

설치

$ npm install dateformat
$ dateformat --help

데모

var dateFormat = require('dateformat');
var now = new Date();

// Basic usage
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM

// You can use one of several named masks
dateFormat(now, "isoDateTime");
// 2007-06-09T17:46:21

// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
dateFormat(now, "hammerTime");
// 17:46! Can't touch this!

// You can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007
...

Use x-date module which is one of sub-modules of x-class library ;

require('x-date') ; 
  //---
 new Date().format('yyyy-mm-dd HH:MM:ss')
  //'2016-07-17 18:12:37'
 new Date().format('ddd , yyyy-mm-dd HH:MM:ss')
  // 'Sun , 2016-07-17 18:12:51'
 new Date().format('dddd , yyyy-mm-dd HH:MM:ss')
 //'Sunday , 2016-07-17 18:12:58'
 new Date().format('dddd ddSS of mmm , yy')
  // 'Sunday 17thth +0300f Jul , 16'
 new Date().format('dddd ddS  mmm , yy')
 //'Sunday 17th  Jul , 16'

Alternative #6233....

Add the UTC offset to the local time then convert it to the desired format with the toLocaleDateString() method of the Date object:

// Using the current date/time
let now_local = new Date();
let now_utc = new Date();

// Adding the UTC offset to create the UTC date/time
now_utc.setMinutes(now_utc.getMinutes() + now_utc.getTimezoneOffset())

// Specify the format you want
let date_format = {};
date_format.year = 'numeric';
date_format.month = 'numeric';
date_format.day = '2-digit';
date_format.hour = 'numeric';
date_format.minute = 'numeric';
date_format.second = 'numeric';

// Printing the date/time in UTC then local format
console.log('Date in UTC: ', now_utc.toLocaleDateString('us-EN', date_format));
console.log('Date in LOC: ', now_local.toLocaleDateString('us-EN', date_format));

I'm creating a date object defaulting to the local time. I'm adding the UTC off-set to it. I'm creating a date-formatting object. I'm displaying the UTC date/time in the desired format:

enter image description here


I needed a simple formatting library without the bells and whistles of locale and language support. So I modified

http://www.mattkruse.com/javascript/date/date.js

and used it. See https://github.com/adgang/atom-time/blob/master/lib/dateformat.js

The documentation is pretty clear.


I think this actually answers your question.

It is so annoying working with date/time in javascript. After a few gray hairs I figured out that is was actually pretty simple.

var date = new Date();
var year = date.getUTCFullYear();
var month = date.getUTCMonth();
var day = date.getUTCDate();
var hours = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();

var ampm = hours >= 12 ? 'pm' : 'am';
hours = ((hours + 11) % 12 + 1);//for 12 hour format

var str = month + "/" + day + "/" + year + " " + hours + ":" + min + ":" + sec + " " + ampm;
var now_utc =  Date.UTC(str);

Here is a fiddle


appHelper.validateDates = function (start, end) {
    var returnval = false;

    var fd = new Date(start);
    var fdms = fd.getTime();
    var ed = new Date(end);
    var edms = ed.getTime();
    var cd = new Date();
    var cdms = cd.getTime();

    if (fdms >= edms) {
        returnval = false;
        console.log("step 1");
    }
    else if (cdms >= edms) {
        returnval = false;
        console.log("step 2");
    }
    else {
        returnval = true;
        console.log("step 3");
    }
    console.log("vall", returnval)
    return returnval;
}

참고URL : https://stackoverflow.com/questions/10645994/how-to-format-a-utc-date-as-a-yyyy-mm-dd-hhmmss-string-using-nodejs

반응형