简体   繁体   中英

Split date/time strings

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

eg date = "12/8/2012" & time = "11:25 am"

To put this into the android calendar, I need to do the following:

Calendar beginTime = Calendar.getInstance();
beginTime.set(year, month, day, hour, min);
startMillis = beginTime.getTimeInMillis();
intent.put(Events.DTSTART, startMillis);

How can I split the date and time variables so that they are useable in the "beginTime.set() " method?

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();
        }
    }
}

Try this:

String date = "12/8/2012";
String time = "11:25 am";

String[] date1 = date.split("/");
String[] time1 = time.split(":");
String[] time2 = time1[1].split(" ");  // to remove am/pm

Calendar beginTime = Calendar.getInstance();
beginTime.set(Integer.parseInt(date1[2]), Integer.parseInt(date1[1]), Integer.parseInt(date1[0]), Integer.parseInt(time1[0]), Integer.parseInt(time2[0]));
startMillis = beginTime.getTimeInMillis();
intent.put(Events.DTSTART, startMillis);

Hope this helps.

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!

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..

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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