简体   繁体   English

使用正则表达式提取和重新格式化时间戳的唯一方法?

[英]Using regex to extract and reformat timestamp the only way?

I need to read a list of timestamps and sort them by "oldest" and "newest" order. 我需要阅读时间戳列表,并按“最旧”“最新”顺序对其进行排序。 But before I can sort them, I need to reformat them first. 但是在对它们进行排序之前,我需要先对其重新格式化。 Those timestamps are in the following format: 这些时间戳采用以下格式:

mm:hh PM/AM dd Month(egJun) yyyy , mm:hh PM / AM dd月(egJun)yyyy

For example: 例如:

  • 3:40 PM 1 Jun 2016 2016年6月1日下午3:40
  • 11:40 AM 11 Jun 2016 2016年6月11日11:40

I am using Regex to extract and reformat each timestamp into a format that Java will recognize, eg dd Month(eg Jun) yyyy hh:mm 我正在使用Regex提取每个时间戳并将其重新格式化为Java可以识别的格式,例如dd月(例如Jun)yyyy hh:mm

What I have done is as following: 我所做的如下:

package regularExpressionDate;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class regularExpressionDate {

    public static void main(String[] args) {
        String pattern = "^(\\d{1,2}):(\\d{1,2})\\s(PM|AM)\\s(\\d{1,2})\\s(\\w{3})\\s(\\d{4})$";
        String date1 = "3:40 PM 1 Jun 2016";
        String newDate1;
        int hour;

        Pattern r = Pattern.compile(pattern);
        Matcher m1 = r.matcher(date1);

        if(m1.find()) {
            hour = Integer.parseInt(m1.group(1));
            if(m1.group(3).equals("PM")) {
                hour+=12;
                System.out.println(m1.group(3));
            }
            newDate1 = (m1.group(4) + " " + m1.group(5) + " " + m1.group(6) + " " + hour + ":" + m1.group(2));
            System.out.println(newDate1);
        }
        else {
            System.out.println("No match");
        }
    }
}

For input 3:40 PM 1 Jun 2016 , I got 1 Jun 2016 15:40 . 对于3:40 PM 1 Jun 2016 1 Jun 2016 15:40 3:40 PM 1 Jun 2016输入,我得到了1 Jun 2016 15:40

My question is: 我的问题是:

  • Is my approach the best way to achieve my goal in terms of clarity and efficiency? 就清晰度和效率而言,我的方法是实现目标的最佳方法吗? I was hoping there would a method that could convert into Java recognized timestamp format right away, but I did not find it. 我希望有一种方法可以立即转换为Java识别的时间戳格式,但是我没有找到它。

You can use the Stream API to parse and sort multiple dates 您可以使用Stream API解析和排序多个日期

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a d MMM yyyy");
List<LocalDateTime> dates =
        Stream.of("3:40 PM 1 Jun 2016", "11:40 AM 11 Jun 2016")
                .map(text -> LocalDateTime.parse(text, formatter))
                .sorted()
                .collect(Collectors.toList());
System.out.println(dates);

prints 版画

[2016-06-01T15:40, 2016-06-11T11:40]

I went this way using parser. 我使用解析器以这种方式。

    LocalDateTime ldt = LocalDateTime.parse("11:40 AM 11 Jun 2016", DateTimeFormatter.ofPattern("h:m a d MMM yyyy"));
    System.out.println(ldt);

If you have multiple white spaces, you can clear input before parsing 如果您有多个空格,则可以在解析之前清除输入

 String inputDate = "11:40    AM    11   Jun 2016";
 inputDate = inputDate.replaceAll("[ ]+", " ");

For multiple dates, move formatter. 对于多个日期,请移动格式化程序。

 //BTW, it is thread-safe.
 private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("h:m a d MMM yyyy");


 //---
 LocalDateTime ldt = LocalDateTime.parse(input, FORMATTER);

You can parse your date String to Java Date by using SimpleDateFormat 您可以使用SimpleDateFormat将日期字符串解析为Java Date

    String date = "3:40 PM 1 Jun 2016";

    SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a dd MMM yyyy");
    Date startDate = formatter.parse(date);
    System.out.println(startDate);

After this you can sort date objects using comparator. 之后,您可以使用比较器对日期对象进行排序。

You can do something like this : 您可以执行以下操作:

Convert string dates to Date and then add them to a list (collection) and sort them. 将字符串日期转换为Date ,然后将其添加到列表(集合)中并对其进行排序。

Check out the working example here !! 在这里查看工作示例!

    // Your dates to sort
    String dates[] = {"3:40 PM 1 Jun 2016", "11:40 AM 11 Jun 2016"}; 

    List<Date> lst = new ArrayList<>();
    // Your date format
    DateFormat format = new SimpleDateFormat("hh:mm a dd MMM yyyy"); 

    for(String str : dates){
        //creating the collection of your dates converted to java dates
        lst.add(format.parse(str)); 
    }

    //sorting  the dates
    Collections.sort(lst);

    //converting the dates into new format (if required)
    DateFormat newFormat = new SimpleDateFormat("dd MMM yyyy HH:mm");
    for(Date date : lst){
        System.out.println(newFormat.format(date));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM