How to format date and time in Android?

前端 未结 24 1623
面向向阳花
面向向阳花 2020-11-22 00:51

How to format correctly according to the device configuration date and time when having a year, month, day, hour and minute?

24条回答
  •  野性不改
    2020-11-22 01:27

    The android Time class provides 3 formatting methods http://developer.android.com/reference/android/text/format/Time.html

    This is how I did it:

    /**
    * This method will format the data from the android Time class (eg. myTime.setToNow())   into the format
    * Date: dd.mm.yy Time: hh.mm.ss
    */
    private String formatTime(String time)
    {
        String fullTime= "";
        String[] sa = new String[2];
    
        if(time.length()>1)
        {
            Time t = new Time(Time.getCurrentTimezone());
            t.parse(time);
            // or t.setToNow();
            String formattedTime = t.format("%d.%m.%Y %H.%M.%S");
            int x = 0;
    
            for(String s : formattedTime.split("\\s",2))
            {   
                System.out.println("Value = " + s);
                sa[x] = s;
                x++;
            }
            fullTime = "Date: " + sa[0] + " Time: " + sa[1];
        }
        else{
            fullTime = "No time data";
        }
        return fullTime;
    }
    

    I hope thats helpful :-)

提交回复
热议问题