0

I am writing an application that stores a series of values in an Array List object. All of the values are stored as Strings in the array, and one of the parameters is a time stamp which is prefixed with "Timestamp: " followed by the actual Unix timestamp (e.g. 1556849753564)

I need to parse only the Unix timestamp from the Timestamp String object.

Here is what I have tried:

public void parseTimestamp() {
    String lastBlockTimeAsString = (String) HashArray.hashArray.get(HashArray.hashArray.size() - 12);
    char[] timeAsCharArray = lastBlockTimeAsString.toCharArray();
    long lastBlockTime = Long.parseLong(String.valueOf(timeAsCharArray[12] + timeAsCharArray[13] ..... etc ));
}

The HashArray.hashArray.get() call is just pulling the Timestamp object from the Array List. I am pulling the 12th character from the array because that is the start of the timestamp.

In Python I could do something like:

timeAsCharArray[12]:[24] 

How can I accomplish this in Java more elegantly than the solution I came up with, which is basically to concatenate each individual character from the array.. Any help would be appreciated!

3
  • 1
    Would this help you: String timeStampString = "Timestamp: 1556849753564"; String strgTime = timeStampString.split(":\\s+")[1].trim(); long lastBlockTime = Long.parseLong(strgTime);? Commented May 3, 2019 at 3:18
  • Let me try this out and get back to you. Thank you for your response! Commented May 3, 2019 at 3:22
  • Btw, Its timeAsCharArray[12:24] Commented Aug 20, 2020 at 11:22

1 Answer 1

1

Not sure why you are trying to convert a string to a character array and then concatenate again. As noted by DevilsHnd, you could either split by removing the "Timestamp: " prefix and getting the "Unix time" or you could replace and then cast. Remember, this assumes that after the replace, user will always have Long numeric value

long lastBlockTime = Long.parseLong(lastBlockTimeAsString.replace("Timestamp: ",""));

Sign up to request clarification or add additional context in comments.

3 Comments

I think this is going to be what I need. Yes, the timestamp is a long before it gets written to the Array List, and I need it to be parsed back as a long so I can subtract the timestamp in the Array List before the most recent one, from the most recent one. I will try this and let you know if it works, thank you!
If this solved your issue, please accept the answer.
Yup, I just tested it out and got it working. Can't believe I missed that 'replace' method. Thanks a million!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.