如何将 LocalTime 转换为 String 以将其添加到数组中

How to convert LocalTime to String to add it to an array

我想将当前时间添加到字符串数组中,但是

LocalTime.now(ZoneId.of("GMT"));

提供类型LocalTime,要求类型为字符串。如何将本地时间转换为字符串?

你可以使用LocalTime的toString()方法,或者format()方法 在这里查看更多信息:https://developer.android.com/reference/java/time/LocalTime

对于默认格式,您可以简单地使用LocalTime#toString。但是,如果您需要自定义格式的字符串,则必须使用 DateTimeFormatter.

演示:

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));
    }
}

输出:

[15:50:10.106099, 03:50:10 PM, null]