Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove leading zero from time(hours)

Tags:

java

time

zero

hour

I want to have the hour from 1-9 without the leading zero, but the minutes with the zero while also adding 15 minutes to the time. Right now, when I input 1 and 46 i get 02:01, and i want to get 2:01

Scanner scan = new Scanner(System.in);
int hour = scan.nextInt();
int minutes = scan.nextInt();
LocalTime time = LocalTime.of(hour , minutes);
time = time.plusMinutes(15);
System.out.println(time);
like image 212
MickeyMoise Avatar asked Apr 02 '20 20:04

MickeyMoise


People also ask

How do I remove leading zeros in SQL?

Basically it performs three steps: Replace each 0 with a space – REPLACE([CustomerKey], '0', ' ') Use the LTRIM string function to trim leading spaces – LTRIM(<Step #1 Result>) Lastly, replace all spaces back to 0 – REPLACE(<Step #2 Result>, ' ', '0')

How do I remove leading zeros in CPP?

To consider this in, use: str. erase(0, min(str. find_first_not_of('0'), str.

How do I get rid of 0.01 in Excel?

In Excel, if you want to remove the leading zeros before decimal point, you can apply the Format Cells function. Note: . 00 indicates to retain two numbers after decimal point, you can change it to . 000 or .


Video Answer


2 Answers

You can use DateTimeFormatter with format "H:mm" https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatter.html

DateTimeFormatter.ofPattern("H:mm").format(LocalTime.now())

Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding. Otherwise, the count of digits is used as the width of the output field, with the value zero-padded as necessary. The following pattern letters have constraints on the count of letters. Only one letter of 'c' and 'F' can be specified. Up to two letters of 'd', 'H', 'h', 'K', 'k', 'm', and 's' can be specified. Up to three letters of 'D' can be specified.

like image 133
Alexander Terekhov Avatar answered Oct 02 '22 00:10

Alexander Terekhov


When you print time directly, it uses the toString() method of LocalTime, which is documented as:

The output will be one of the following ISO-8601 formats:

  • HH:mm
  • HH:mm:ss
  • HH:mm:ss.SSS
  • HH:mm:ss.SSSSSS
  • HH:mm:ss.SSSSSSSSS

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

Since you want the hour to not be zero-prefixed, you need to specify the format yourself, by calling the format(...) method instead of the toString() method.

E.g.

System.out.println(time.format(DateTimeFormatter.ofPattern("H:mm")));
like image 20
Andreas Avatar answered Oct 01 '22 23:10

Andreas