반응형
JavaScript에서 Date ()를 가장 가까운 5 분으로 반올림
Date()
인스턴스를 사용하여 시간을 가장 가까운 5 분으로 반올림하려면 어떻게해야합니까?
예 : 오후 4시 47 분이면 시간을 오후 4시 45 분으로 설정합니다.
이미 Date
개체 가있는 경우 매우 간단 합니다.
var coeff = 1000 * 60 * 5;
var date = new Date(); //or use any other date
var rounded = new Date(Math.round(date.getTime() / coeff) * coeff)
가장 가까운 x 분으로 반올림
다음은 날짜 개체를 가장 가까운 x 분으로 반올림하거나 날짜를 지정하지 않으면 현재 시간을 반올림하는 메서드입니다.
let getRoundedDate = (minutes, d=new Date()) => {
let ms = 1000 * 60 * minutes; // convert minutes to ms
let roundedDate = new Date(Math.round(d.getTime() / ms) * ms);
return roundedDate
}
// USAGE //
// Round existing date to 5 minutes
getRoundedDate(5, new Date()); // 2018-01-26T00:45:00.000Z
// Get current time rounded to 30 minutes
getRoundedDate(30); // 2018-01-26T00:30:00.000Z
대답하기에는 조금 늦었지만 누군가에게 도움이 될 수 있습니다. 다음과 같이 분을 취하면
new Date().getMinutes()
지난 5 분 동안
new Date().getMinutes() - (new Date().getMinutes()%5)
ES6 및 부분 기능을 사용하면 우아 할 수 있습니다.
const roundDownTo = roundTo => x => Math.floor(x / roundTo) * roundTo;
const roundUpTo = roundTo => x => Math.ceil(x / roundTo) * roundTo;
const roundDownTo5Minutes = roundDownTo(1000*60*5);
const ms = roundDownTo5Minutes(new Date())
console.log(new Date(ms)); // Wed Jun 05 2019 15:55:00 GMT+0200
최근에 날짜를 시간 프레임으로 반올림하는 매우 효율적인 방법을 찾았습니다.
간단히 말해서 :
// minutes
var tf = 15; // 5,10,13,15, 60, - what ever you want
var dt = DateTime.UtcNow;
var minues = dt.TimeOfDay.TotalMinutes; // use TotalMinutes, TotalSecibds, TotalMillisecons and etc
var roundedMinutes = (minues - (minues%tf));
var roundedDate = dt.Date.AddMinutes(a);
LINQPad에서 약간의 테스트
// minutes
var tf = 15; // 5,10,13,15, 60, - what ever you want
var dt = DateTime.UtcNow;
var minues = dt.TimeOfDay.TotalMinutes;
dt.Dump();
minues.Dump();
(ms%tf).Dump();
var a = (minues - (minues%tf));
a.Dump();
dt.Date.AddMinutes(a).Dump();
산출:
13.07.2018 7:43:58 - current date
463,981443103333 - total mins
13,9814431033333 - rest
450 - rounded minutes value
13.07.2018 7:30:00 - rounded date
There is an NPM package @qc/date-round
that can be used. Given that you have a Date
instance to be rounded
import { round } from '@qc/date-round'
const dateIn = ...; // The date to be rounded
const interval = 5 * 60 * 1000; // 5 minutes
const dateOut = round(dateIn, interval)
Then you can use date-fns
to format the date
import format from 'date-fns/format';
console.log(format(dateOut, 'HH:mm')) // 24-hr
console.log(format(dateOut, 'hh:mm a')) // 12-hr
ReferenceURL : https://stackoverflow.com/questions/10789384/round-a-date-to-the-nearest-5-minutes-in-javascript
반응형
'developer tip' 카테고리의 다른 글
Android에서 비트 맵을 그레이 스케일로 변환 (0) | 2021.01.09 |
---|---|
프로그래밍 방식으로 UINavigationController에서 "뒤로"버튼을 누르는 방법 (0) | 2021.01.09 |
UIButton에서 이미지를 늘리지 않는 방법 (0) | 2021.01.09 |
Twitter Bootstrap 3의 둥근 테이블 (0) | 2021.01.09 |
지정된 시간 후에 URL로 JQuery 리디렉션 (0) | 2021.01.09 |