I want the user to input hours and minutes for a Local.Time from 00 to 23 and from 00 to 59, I scanned this as an int. It works but for values from 00 to 09 the int ignores the 0 and places then as a 0,1,2...9 instead of 00,01,02,03...09; this breaks the Local.Time since, for example "10:3"; is not a valid format for time.
I have read I can format this as a String, but I don't think that helps me since I need an int value to build the LocalTime and subsequent opperations with it.
There is a way of formatting this while kepping the variable as an int??
Can I code this differently to bypass this??
Am I wrong about how these classes work??
I am pretty new to these concepts
Here is the code I am using
int hours;
int minutes;
System.out.println("Input a number for the hours (00-23): ");
hours = scan.nextInt();
System.out.println("Input a number for the minutes (00-59): ");
minutes = scan.nextInt();
LocalTime result = LocalTime.parse(hours + ":" + minutes);
I tried using the NumberFormat class but it returns an error when trying to declare its variables (something like it is an abstract variable and cannot be instanced)
I also tried using the String format but I don't really know what to do with that string after that, it asks me for a int and not a string to build this method
First: an int doesn't differentiate between 09 and 9. They are the same value: the number nine.
Next: if you already have numbers, then going back to a string to produce a date is an anti-pattern: you are losing type checking by this. So instead of using LocalTime.parse and constructing the input from int values, you should simply use LocalTime.of(hours, minutes):
LocalTime result = LocalTime.of(hours, minutes);
tl;dr Use LocalTime.of(hours, minutes), it's most straight-forward
Alternative: Parse with a suitable DateTimeFormatter:
public static void main(String[] args) {
// single-digit example values
int hours = 9;
int minutes = 1;
// define a formatter that parses single-digit hours and minutes
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:m");
// use it as second argument in LocalTime.parse
LocalTime result = LocalTime.parse(hours + ":" + minutes, dtf);
// see the result
System.out.println(result);
}
Output:
09:01
Fix
use the proper DateTimeFormatter
LocalTime.parse(hours + ":" + minutes, DateTimeFormatter.ofPattern("H:m"));
Build the expected default format
LocalTime.parse(String.format("%02d:%02d", hours, minutes));
Improve
Use a more appropriate method
LocalTime.of(hours, minutes);
Related
my method accepts - hours, minutes, seconds and milliseconds separated by sign / as a string parameter
how can I add to the current date the parameters that come to the method.
Example 1: today, 02/10/2021, the method receives metnode data (10/10/10/10) - output - 02/10/2021 10:10:10
Example 2: today, 02/10/2021, the method receives metnode data (55/10/10/10) - output - 02/12/2021 07:10:10
That is, you need to add 55 hours 10 seconds 10 seconds and 10 milliseconds to the current date.
you cannot use the Calendar and StringTokenizer classes.
public void method(String s) {
s = s.replaceAll("/", "-");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss");
final LocalDateTime now = LocalDateTime.parse(s, formatter.withResolverStyle(ResolverStyle.LENIENT));
System.out.println(now);
}
i found the withResolverStyle (ResolverStyle.LENIENT) method
but did not understand how to use it.
A lenient DateTimeFormatter is enough
I don’t know if it’s the best solution. That probably depends on taste. It does use the ResolverStyle.LENIENT that you mentioned and generally works along the lines of the code in your question, only fixed and slightly simplified.
My formatter includes both date and time. This is necessary for surplus hours to be converted to days.
private static final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM-dd H/m/s/")
.appendValue(ChronoField.MILLI_OF_SECOND)
.toFormatter()
.withResolverStyle(ResolverStyle.LENIENT);
Next thing we need a string that matches the formatter. So let’s prepend the date to the time string that we already have got:
String timeString = "55/10/10/10";
LocalDate today = LocalDate.now(ZoneId.of("America/Regina"));
String dateTimeString = "" + today + ' ' + timeString;
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.println(dateTime);
The output from my code when I ran it today (February 10) was:
2021-02-12T07:10:10.010
A different idea: use Duration
Edit: An alternative is to use the Duration class. A reason for doing that would be that it really appears that you are adding a duration rather than setting the time of day. A liability is that parsing your string into a Duration is a bit tricky. The Duration.parse method that we want to use only accepts ISO 8601 format. It goes like PT55H10M10.010S for a period of time of 55 hours 10 minutes 10.010 seconds. And yes, milliseconds need to be given as a fraction of the seconds.
String isoTimeString = timeString.replaceFirst("(/)(\\d+)$", "$100$2")
.replaceFirst("(\\d+)/(\\d+)/(\\d+)/0*(\\d{3})", "PT$1H$2M$3.$4S");
Duration dur = Duration.parse(isoTimeString);
LocalDateTime dateTime = LocalDate.now(ZoneId.of("Asia/Kathmandu"))
.atStartOfDay()
.plus(dur);
When I ran it just now — already February 11 in Kathmandu, Nepal — the output was:
2021-02-13T07:10:10.010
I am using two calls to replaceFirst(), each time using a regular expression. The first call simply adds some leading zeroes to the milliseconds. $1 and $2 in the replacement string give us what was matched by the first and the second group denoted with round brackets in the regular expression.
The second replaceFirst() call established the ISO 8601 format, which includes making sure that the milliseconds are exactly three digits so they work as a decimal fraction of the seconds.
Link: ISO 8601
Try this:
public void method(String s) {
String[] arr = s.split("/");
LocalDateTime now = LocalDateTime.of(
LocalDate.now(), LocalTime.of(0, 0))
.plusHours(Integer.parseInt(arr[0]))
.plusMinutes(Integer.parseInt(arr[1]))
.plusSeconds(Integer.parseInt(arr[2]))
.plusNanos(Integer.parseInt(arr[3]) * 1_000_000L);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
System.out.println(now.format(formatter));
}
Look into the LocalDateTime documentation. It offers various means for combining dates. Such as:
plus(amount, unit)
plusDays(days)
plusHours(hours)
plusMinutes(minutes)
just for simplicity , you can your LocalDateTime class. it is easy to understand. please refer to below code is used to add the hours, minuts, second and nanos to current Date Time.
this Date Time then can easy formatted by any format pattern as required.
public void addDateTime(int hours, int minuts, int seconds, int nanos) {
LocalDateTime adt = LocalDateTime.now();
System.out.println(adt);
adt = adt.plusHours(hours);
adt = adt.plusMinutes(minuts);
adt = adt.plusSeconds(seconds);
adt = adt.plusNanos(nanos);
System.out.println(adt);
}
I know there are similar questions but they don't answer my problem. I want to format the current time into integer, but only the minutes or seconds.
So for example
LocalTime d = LocalTime.now(ZoneId.of("GMT"));
gives me the current GMT and with "withNano(0)" I can cut off the nanoseconds. Since I have it in the format 12:15:45 now I want to be able to save 15 (Minutes) into my Integer or 45 (Seconds). How can I convert it?
You can call specific methods on the LocalTime such as getMinute() and getSecond(), or you can use a DateTimeFormatter with a pattern that you’re looking for, like:
d.format(DateTimeFormatter.of(“mm:ss”);
If you’re doing that, you don’t need to zero out the nano first.
You can use built in methods for getting minutes and seconds, they both return integers:
d.getMinute();
d.getSecond();
Simply use the getter methods of LocalTime.
import java.time.LocalTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
LocalTime now = LocalTime.now(ZoneOffset.UTC);
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
System.out.printf("%d hour, %d minute, %d second", hour, minute, second);
}
}
Output:
21 hour, 37 minute, 47 second
Also, I suggest you use ZoneOffset.UTC for UTC instead of the 3-letter name for timezone. You can also use ZoneId.of("Etc/UTC"). The general naming convention for timezone is Region/City e.g. Europe/London.
I'm currently working with a school-made class that allow the reading of a user input.
Here is my currently code which ask the hour, then the minutes for a car reservation because I need to give the final hour in the format HHhMM:
public class Facturation {
public static void main (String [] args) {
while (true) {
System.out.println(MSG1);
System.out.println (MSG_SOLLICITATION1);
while (true ) {
HrDebut= Clavier.lireInt();
if (HrDebut >= 9 && HrDebut <= 18 ) {
break;
} else {
System.out.println (MSG_ERREUR);
System.out.println (MSG_SOLLICITATION1);
} }
System.out.println (MSG_SOLLICITATION2);
while (true) {
MinDebut=Clavier.lireInt();
if (MinDebut >= 00 && MinDebut <= 59 ){
System.out.println("CONFIRMATION:" + "\n"
+ "Debut de la location:" + HrDebut + "h" + MinDebut
+ "\n" + "\n" + MSG_RTR_MENU) ;
Clavier.lireFinLigne();
break;
So if the user give 9+34, the final output would be: 9h34.
Is there a way to only have the user input 1 number from 900 to 1800 (9am to 18PM) and then give a final output in the format HHhMM?
For example, user input 945 -> final output is 9h45.
Thanks.
java.time
Java has a built-in class representing a time of day, LocalTime, and facilities for parsing a string into a LocalTime and formatting it back into a string. So yes, reading the time as 934 or 1800 goes nicely, and there’s no reason to hand format the way you did in the question.
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("Hmm");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("H'h'mm");
LocalTime minTime = LocalTime.of(9, 0);
LocalTime maxTime = LocalTime.of(18, 0);
String userInput = "1800";
LocalTime time = LocalTime.parse(userInput, inputFormatter);
if (time.isBefore(minTime) || time.isAfter(maxTime)) {
System.out.println("TODO put your error message here");
} else {
String output = time.format(outputFormatter);
System.out.println("Debut de la location: " + output);
}
Output from the example code snippet is:
Debut de la location: 18h00
One detail may surprise here: The input format pattern string Hmm would ordinarily mean input in three digits, one digit hour of day and two digit minute of the hour. However, when Java sees that there are four digits, not three, since it knows that hour of day may sometimes require two digits, it is smart enough to figure that 1800 is two-digit hour, 18, and two-digit minute, 00.
In the output format pattern, H'h'mm, the single quotes around the h means that this letter is to be printed literally, it is not a format pattern letter like H and mm.
If you can, I recommend that you read the input as a String, not an int.
If the user has typed a time that doesn’t conform with the exptected, for instance a wrong format or a minute of hour greater than 59, LocalTime.parse will throw a DateTimeParseException, so you will want to catch this exception, issue an error message and ask the user to try again.
Link: Oracle tutorial: Date Time explaining how to use java.time.
1 - Use scanner class for user input.
Scanner scan= new Scanner(System.in);
2 - ask user to input time in your desired format like 945 or 1230.
3 - then use below method logic in your code to get hour and minute.
public static void t() {
int a = 1945;//suppose your time
int minute = a%100; // your minute data
System.out.println(minute);
int hour = a/100;// your hour data
System.out.println(hour);
}
In this code we have not taken care of wrong input. so if you are not sure that user will always provide correct data, Please implement logic for data corrections check.(like number can not be less than 3 digit or more than 4 digit. time range is 100 to 2400).
If its 1 o'clock - user need to enter 100.
How can I display only the last two digits of the current year without using any substring algorithms or any third party libraries?
I have tried the below method and it gave a four-digit year. I want to know whether there are any date formatting options available to get the current year in two-digit format.
Calendar.getInstance().get(Calendar.YEAR);
You can simply use the modulo operator:
int lastTwoDigits = Calendar.getInstance().get(Calendar.YEAR) % 100;
Edit: Using a SimpleDateFormat, as #R.J proposed, is the better solution if you want the result to be a string. If you need an integer, use modulo.
You can use a SimpleDateFormat to format a date as per your requirements.
DateFormat df = new SimpleDateFormat("yy"); // Just the year, with 2 digits
String formattedDate = df.format(Calendar.getInstance().getTime());
System.out.println(formattedDate);
Edit: Depending on the needs/requirements, either the approach suggested by me or the one suggested by Robin can be used. Ideally, when dealing with a lot of manipulations with the Date, it is better to use a DateFormat approach.
This is a one-liner:
System.out.println(Year.now().format(DateTimeFormatter.ofPattern("uu")));
I am using java.time.Year, one of a number of date and time classes introduced in Java 8 (and also backported to Java 6 and 7). This is just one little example out of very many where the new classes are more convenient and lead to clearer code than the old classes Calendar and SimpleDateFormat.
If you just wanted the two-digit number, not as a string, you may use:Year.now().getValue() % 100.
The other answers were good answers in 2013, but the years have moved on. :-)
Edit: New Year doesn’t happen at the same time in all time zones. To make the dependency on time zone clear in the code I would usually write Year.now(myDesiredTimeZoneId), for example in the form Year.now(ZoneId.systemDefault()).
String.format() also has Date/Time Conversions.
To get the last two digits of the current year,
String.format("%ty", Year.now());
This works with a number of the java.time classes, including Year, YearMonth, LocalDate, LocalDateTime, and ZonedDateTime.
In Kotlin
Call this function and pass time in parameter
Example :
Input Parameter : "2021-08-09T16:01:38.905Z"
Output : 09 Aug 21
private val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
private val outputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
fun calculateDateMonthYear(time: String): String {
val inputTime = inputFormat.parse(time)
val convertDateMonthYear = outputFormat.format(inputTime!!)
val timeInMilliseconds = outputFormat.parse(convertDateMonthYear)!!
val mTime: Calendar = Calendar.getInstance()
mTime.timeInMillis = timeInMilliseconds.time
val date_cal = SimpleDateFormat("dd")
val month_date = SimpleDateFormat("MMM")
val year_cal = SimpleDateFormat("yy")
val date = date_cal.format(mTime.time)
val month_name = month_date.format(mTime.time)
val year = year_cal.format(mTime.time)
return "$date $month_name $year"
}
The solution of #Robin Krahl is a bit hacky but I like it. We could avoid the cases commented by #Albert Tong if we add a leading zero. In order that we have the last two digits of the year, I suppose that the result should be a String. In case we could not use the solution of #jaco0646. We could do this:
String yearStr = addLeadingZero(Calendar.getInstance().get(Calendar.YEAR) % 100)
private String addLeadingZero(int num) {
String result = String.valueOf(num);
if(num < 10){
result = "0" + result;
}
return result;
}
I know the question asked for how to do this in Java but Google sent me here when asking about Groovy, so I'll add my answer for that here.
I came up with this based on the Java answer provided by Rahul:
String lastTwoYearDigits = new Date().format("yy")
I'm trying to format a time using a variable input. If a user enter an hour as 1 - 9 the out put would include a "0", and the same for minutes. So far if a user enters 1 hour 3 minutes the output reads 1:3 instead of 01:03.
How do I get the extra 0 in front of numbers less than 10.
Here's the code.....
import java.util.Scanner;
public class FormatTime {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int MinutesInput;
int HoursInput;
int Hours;
int Minutes;
{
System.out.println("Enter hours between 1 and 24");
Hours = input.nextInt();
System.out.println("Enter minutes between 1 and 59");
Minutes = input.nextInt();
{
**//THIS NEXT LINE IS THE PROBLEM**
HoursInput = Hours < 10 ? "0" + Hours : Hours;
System.out.print(HoursInput + ":");
}
{
**//THIS NEXT LINE IS THE PROBLEM**
MinutesInput = (Minutes < 10) ? "0" + Minutes : (Minutes);
System.out.print(MinutesInput);
}
System.out.println();
}
}
}
How do I get the extra 0 in front of numbers less than 10.
You don't, while the target variable is of type int. An int is just a number, not a string - whereas "0" + Hours is a string.
int values don't contain any sort of string representation - the number sixteen is just as much "0x10" or "0b10000" as it is "16"... or even "00016" if your decimal representation allows much digits. ("00016" may be mis-interpreted as fourteen, however, if it's parsed as an octal string...)
Use DecimalFormat to convert numbers into strings in your desired format, or String.format, or possibly just PrintStream.printf if you want to write it straight to the console.
I'd also strongly recommend that you use camelCase for your local variables, and only declare them when you first need them.
Perhaps you should be using
System.out.printf("%02d:%02d%n", Hours, Minutes);
You are confusing int and String types:
int HoursInput;
//...
HoursInput = Hours < 10 ? "0" + Hours : Hours;
There are two problems with your code: you are trying to store string "07" (or similar) in an int. Secondly even if it was possible, 07 is equivalent to 7 as far as integer types are concerned (well, leading 0 has a special octal meaning, but that's not the point).
Try this instead:
String hoursInput;
//...
hoursInput = Hours < 10 ? "0" + Hours : "" + Hours;
you must use String variables or use format method (similar to sprintf from c) from String class.
String time = String.format("%02d:%02d", hours, minutes );