Split date/time strings
Asked Answered
B

7

8

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

Britneybritni answered 7/8, 2013 at 9:12 Comment(1)
Use String.split method.Verne
V
9

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();
        }
    }
}
Veldaveleda answered 7/8, 2013 at 9:30 Comment(0)
H
4

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.

Hillegass answered 7/8, 2013 at 9:17 Comment(1)
This will work, but Calendar.set expects integers. Therefore you should use Integer.parseInt(date1[x]); in the set method. EDIT: Also just noticed that Calendar uses a 24hr clock, so you would also need to convert time2[0] from 12 to 24hr based on am/pm in time2[1]Bunting
R
2

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!

Ribbon answered 7/8, 2013 at 9:17 Comment(0)
B
0

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

Bihari answered 7/8, 2013 at 9:16 Comment(0)
I
0

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

Introit answered 7/8, 2013 at 9:18 Comment(0)
W
0

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);
Whipstitch answered 7/8, 2013 at 9:39 Comment(0)
S
0

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

Sternutation answered 9/10, 2020 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.