-2

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?

xiaofeng
  • 41
  • 1
  • 10
  • 4
    Use `LocalTime#toString()`...? If you need it in a different format then use `DateTimeFormatter`. But the better option is to store the `LocalTime` itself. – Slaw Jan 17 '21 at 15:23
  • 2
    It's not clear to me what this has to do with the title of your question. Please edit appropriately so that the title and body of the question are consistent. – Jon Skeet Jan 17 '21 at 15:23
  • 1
    Why not try the LocalTime.toString() or LocalTime.format(DateTimeFormatter)? – ocrdu Jan 17 '21 at 15:23
  • 2
    You don’t want to add your times as strings to your array (except if you need it for an API that requires a string array). Make yourself a `LocalTime[]`, an array of `LocalTime` objects. You can always format each later if you need it for presentation or for interchange with another system. – Ole V.V. Jan 17 '21 at 15:35

2 Answers2

4

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]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

You can use toString() method of LocalTime, or format() method Check more in here: https://developer.android.com/reference/java/time/LocalTime

NhatVM
  • 1,964
  • 17
  • 25
  • Ok thanks. How do I use it? LocalTime.parse("GMT").toString();; works but where is it saved and how do I access it? – xiaofeng Jan 17 '21 at 15:37
  • @xiaofeng That question indicates a lack of fundamental knowledge. If you truly don't understand how `LocalTime#toString()`, object references, and arrays work then I suggest (re)visiting tutorials, videos, books, and other sources covering the basics of Java. This comment is not meant to belittle you nor your efforts, but it's important to understand the basics before moving on to more complex ideas. – Slaw Jan 17 '21 at 16:57
  • thought it doesnt matter because the question is a duplicate – xiaofeng Jan 18 '21 at 03:21