Quantcast
Viewing latest article 11
Browse Latest Browse All 12

Answer by BrianKeys for How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

java.time

Those java.util.Date answers at the top need to go. Here's some code I wrote that deals with different formats. It's also easier to go with a working example:

package com.brian.TimeZoneUtil;import java.time.*;import java.time.format.*;import java.time.LocalDateTime;public class TimeZoneConversion {        public static void main(String[] args) {            String inSlashDateString = "10/31/201100:00:00";            String inHyphenDateString = "2011-10-31T01:01:01";            String inEpochDateString = "1687170164410";            DateTimeFormatter slashFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyyHH:mm:ss");            DateTimeFormatter hyphenFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");            ZonedDateTime epochDateTime = Instant.ofEpochMilli(Long.parseLong(inEpochDateString)).atZone(ZoneId.of("America/Indiana/Indianapolis"));            System.out.println(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss").format( LocalDateTime.parse(inSlashDateString +"00:00:00", slashFormatter)));            System.out.println(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss").format( LocalDateTime.parse(inHyphenDateString, hyphenFormatter)));            System.out.println(epochDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss")));        }}

Viewing latest article 11
Browse Latest Browse All 12

Trending Articles