
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Forming the nearest time using current time in JavaScript
Problem
We are required to write a JavaScript function that takes in a string, time, that represents time in the "HH:MM" form.
Our function is supposed to form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.
For example, if the input to the function is
Input
const time = '19:34';
Output
const output = '19:39';
Output Explanation
The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later.
Example
Following is the code −
const time = '19:34'; const findClosestTime = (time = '') => { const [a, b, c, d] = [time[0], time[1], time[3], time[4]].map(x =>Number(x)); const sorted = [a, b, c, d].sort((x, y) => x - y) const d2 = sorted.find(x => x > d) if (d2 > d) { return `${a}${b}:${c}${d2}` } const c2 = sorted.find(x => x > c && x <= 5) const min = Math.min(a, b, c, d) if (c2 > c) { return `${a}${b}:${c2}${min}` } const b2 = sorted.find(x => x > b && a * 10 + x <= 24) if (b2 > b) { return `${a}${b2}:${min}${min}` } const a2 = sorted.find(x => x > a && x <= 2) if (a2 > a) { return `${a2}${min}:${min}${min}` } return `${min}${min}:${min}${min}` }; console.log(findClosestTime(time));
Output
19:39
- Related Questions & Answers
- How to get the current time in millisecond using JavaScript?
- How to set current time to some other time in JavaScript?
- How to get current date and time using JavaScript?
- Get current date/time in seconds - JavaScript?
- Getting current time in Python
- Java Program to display Current Time in another Time Zone
- How to get current date and time in JavaScript?
- MySQL - Insert current date/time?
- How do I get the current date and time in JavaScript?
- Program to find nearest time by reusing same digits of given time in python
- Get current time information in Java
- Current Date and Time in Perl
- How to get current date/time in seconds in JavaScript?
- How to print current date and time using Python?
- How to extract the number of minutes from current time in JavaScript?
Advertisements