在添加时间时需要以24小时格式获取时间

时间:2011-08-16 12:49:05

标签: android

我已经编写了一个添加时间的函数,如下所示

private void Delay15Minute() {
        String pkManifest = manifest.pkManifestNo;
        manifest_helper = new manifest_helper(this);
        cursor = manifest_helper.GetDeliveries(pkManifest);
        cursor.moveToFirst();
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.getString(cursor.getColumnIndex("PKDelivery"));
            // String
            // RevisedTime=cursor.getString(cursor.getColumnIndex("RevisedEstimatedDeliveryTime"));
            String RevisedTime = "12:55";

            // get hour and minute from time string
            StringTokenizer st1 = new StringTokenizer(RevisedTime, ":");
            int j = 0;
            int[] val = new int[st1.countTokens()];
            // iterate through tokens
            while (st1.hasMoreTokens()) {
                val[j] = Integer.parseInt(st1.nextToken());
                j++;
            }
            // call time add method with current hour, minute and minutesToAdd,
            // return added time as a string
            String date = addTime(val[0], val[1], 15);
            // Tioast the new time
            Toast.makeText(this, "date is =" + date, Toast.LENGTH_SHORT).show();

        }
            }



public String addTime(int hour, int minute, int minutesToAdd) {
        Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
        calendar.add(Calendar.MINUTE, minutesToAdd);
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
        String date = sdf.format(calendar.getTime());

        return date;
    }

我得到的时间为01:10,为12小时... ...

我需要以13:10格式获得它,即24小时格式.....请帮帮我

3 个答案:

答案 0 :(得分:49)

您在hh模式中使用了SimpleDateFormat。这是12小时的格式。请改用kk,以24小时格式为您提供一天中的小时数。请参阅SimpleDateFormat

答案 1 :(得分:39)

只需创建Calendar的实例并获得24小时的时间,

Calendar c = Calendar.getInstance();

int Hr24=c.get(Calendar.HOUR_OF_DAY);
int Min=c.get(Calendar.MINUTE);

答案 2 :(得分:6)

使用此代码

long date = System.currentTimeMillis();

SimpleDateFormat date1 = new SimpleDateFormat("dd-MM-yyyy"); // for current date
SimpleDateFormat time1 = new SimpleDateFormat("kk:mm:ss");  // for 24 hour time
SimpleDateFormat time2 = new SimpleDateFormat("hh:mm:ss");  // for 12 hour time 

String dateString = date1.format(date);    //This will return current date in 31-12-2018 format
String timeString1 = time1.format(date);  //This will return current time in 24 Hour format
String timeString2 = time2.format(date);  //This will return current time in 12 Hour format

Log.e("TAG_1", "24 hour Time - " + timeString1);
Log.e("TAG_1", "24 hour Time - " + timeString1);
Log.e("TAG_1", "dd-MM-yyyy Date format - " + dateString);

而不是打开logcat来检查结果。