I want to add the current time to an array of strings but
LocalTime.now(ZoneId.of("GMT"));
provides the type LocalTime and the required type is a string. How can I convert Localtime into String?
I want to add the current time to an array of strings but
LocalTime.now(ZoneId.of("GMT"));
provides the type LocalTime and the required type is a string. How can I convert Localtime into String?
For the default format, you can simply use LocalTime#toString
. However, if you need the string in a custom format, you will have to use DateTimeFormatter
.
Demo:
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalTime now = LocalTime.now(ZoneOffset.UTC);
// An String [] of size 3
String[] arr = new String[3];
// Add the string representation in default format
arr[0] = now.toString();
// Add the string representation in a custom format
arr[1] = now.format(DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.ENGLISH));
System.out.println(Arrays.toString(arr));
}
}
Output:
[15:50:10.106099, 03:50:10 PM, null]
You can use toString() method of LocalTime, or format() method Check more in here: https://developer.android.com/reference/java/time/LocalTime