How to parse dates in multiple formats using SimpleDateFormat

前端 未结 12 1491
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 08:41

I am trying to parse some dates that are coming out of a document. It would appear users have entered these dates in a similar but not exact format.

here are the for

12条回答
  •  不思量自难忘°
    2020-11-22 09:29

    Using DateTimeFormatter it can be achieved as below:

    
    import java.text.SimpleDateFormat;
    import java.time.LocalDateTime;
    import java.time.ZoneOffset;
    import java.time.ZonedDateTime;
    import java.time.format.DateTimeFormatter;
    import java.time.temporal.TemporalAccessor;
    import java.util.Date;
    import java.util.TimeZone;
    
    public class DateTimeFormatTest {
    
        public static void main(String[] args) {
    
            String pattern = "[yyyy-MM-dd[['T'][ ]HH:mm:ss[.SSSSSSSz][.SSS[XXX][X]]]]";
            String timeSample = "2018-05-04T13:49:01.7047141Z";
            SimpleDateFormat simpleDateFormatter = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            TemporalAccessor accessor = formatter.parse(timeSample);
            ZonedDateTime zTime = LocalDateTime.from(accessor).atZone(ZoneOffset.UTC);
    
            Date date=new Date(zTime.toEpochSecond()*1000);
            simpleDateFormatter.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
            System.out.println(simpleDateFormatter.format(date));       
        }
    }
    

    Pay attention at String pattern, this is the combination of multiple patterns. In open [ and close ] square brackets you can mention any kind of patterns.

提交回复
热议问题