Android Date and Time manipulation - Add, Subtract and Format

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//Add certain number of days to Today
        int myDays = 3;
 
        final Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, myDays);  // number of days to add
        int newDate =     (c.get(Calendar.YEAR) * 10000) +
                            ((c.get(Calendar.MONTH) + 1) * 100) +
                            (c.get(Calendar.DAY_OF_MONTH));
 
 
//Subtract certain number of days to Today
        int myDays = 3;
 
        final Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, (myDays * -1));  // number of days to subtract
        int newDate =     (c.get(Calendar.YEAR) * 10000) +
                            ((c.get(Calendar.MONTH) + 1) * 100) +
                            (c.get(Calendar.DAY_OF_MONTH));
 
 
//Change date format from yyyyMMdd to MM/dd/yy
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
            Date date = null;
            try {
                date = df.parse(inputDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            TextView dateText = (TextView) historyData.findViewById(R.id.mydate);
            dateText.setText(DateFormat.format("MM/dd/yy",date));
 
 
//Change time format from military Hmmss to hh:mm:ss a
 
        SimpleDateFormat df2 = new SimpleDateFormat("Hmmss");
            Date date2 = null;
            try {
                date2 = df2.parse(inputTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            TextView timeText = (TextView) historyData.findViewById(R.id.mytime);
            timeText.setText(DateFormat.format("hh:mm:ss a",date2));

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.