Split date/time strings

后端 未结 7 1845
不思量自难忘°
不思量自难忘° 2020-12-18 03:32

I have a ReST service which downloads information about events in a persons calendar...

When it returns the date and time, it returns them as a string

e.g. d

相关标签:
7条回答
  • 2020-12-18 03:40

    I don't thinks you really need how to split the string, in your case it should be 'how to get time in milliseconds from date string', here is an example:

    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    
    public class DateTest {
    
        public static void main(String[] args) {
            String date = "12/8/2012";
            String time = "11:25 am";
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
            try {
                Date dt = df.parse(date + " " + time);
                Calendar ca = Calendar.getInstance();
                ca.setTime(dt);
                System.out.println(ca.getTimeInMillis());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-18 03:45

    Use SimpleDateFormat (check api docs). If you provide proper time pattern it will be able to convert string into Date instantly.

    0 讨论(0)
  • 2020-12-18 03:46

    Assuming you get your date in String format (if not, convert it!) and then this:

    String date = "12/8/2012";
    String[] dateParts = date.split("/");
    String day = dateParts[0]; 
    String month = dateParts[1]; 
    

    Similarly u can split time as well!

    0 讨论(0)
  • 2020-12-18 03:56

    You can see an example of split method here : How to split a string in Java

    Then simply use the array for your parameter eg: array[0] for year and etc..

    0 讨论(0)
  • 2020-12-18 03:57

    This is just a Idea, you can do some thing like this without splitting

        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm a");
        Date date = formatter.parse("12/8/2012 11:25 am");      
        Calendar cal=Calendar.getInstance();
        cal.setTime(date);
    
    0 讨论(0)
  • 2020-12-18 03:59

    java.time either through desugaring or through ThreeTenABP

    Consider using java.time, the modern Java date and time API, for your date and time work. With java.time it’s straightforward to parse your two strings for date and time individually and then combine date and time into one object using LoalDate.atTime().

    The way I read your code you are really after a count of milliseconds since the epoch. So this is what I am giving you in the first snippet. Feel free to take it apart and use only the lines you need.

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
        DateTimeFormatter timeFormatter = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendPattern("h:mm a")
                .toFormatter(Locale.ENGLISH);
        
        String dateString = "12/8/2012";
        String timeString = "11:25 am";
        
        LocalDate date = LocalDate.parse(dateString, dateFormatter);
        LocalTime time = LocalTime.parse(timeString, timeFormatter);
        long startMillis = date
                .atTime(time)
                .atZone(ZoneId.systemDefault())
                .toInstant()
                .toEpochMilli();
        
        System.out.println(startMillis);
    

    When running in my time zone (at UTC offset +02:00 in August) the output is:

    1344763500000

    For anyone reading along that does need the individual numbers from the two strings, getting those is straightforward too. For example:

        int year = date.getYear();
        Month month = date.getMonth();
        int monthNumber = date.getMonthValue();
        int dayOfMonth = date.getDayOfMonth();
        int hourOfDay = time.getHour();
        int hourWithinAmOrPm = time.get(ChronoField.HOUR_OF_AMPM);
        int minute = time.getMinute();
        
        System.out.format("Year %d month %s or %d day %d hour %d or %d AM/PM minute %d%n",
                year, month, monthNumber, dayOfMonth, hourOfDay, hourWithinAmOrPm, minute);
    

    Year 2012 month AUGUST or 8 day 12 hour 11 or 11 AM/PM minute 25

    Question: Doesn’t java.time require Android API level 26?

    java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

    • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
    • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
    • On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.

    Links

    • Oracle tutorial: Date Time explaining how to use java.time.
    • Java Specification Request (JSR) 310, where java.time was first described.
    • ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
    • Java 8+ APIs available through desugaring
    • ThreeTenABP, Android edition of ThreeTen Backport
    • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
    0 讨论(0)
提交回复
热议问题