0

Does anyone know how to implement this SQL code in Java code?

to_char(to_date(time,'sssss'),'hh24:mi')

Time format is like 36000 in database and then after this sql command it is: 10:00

I want to make this function work in Java not SQL.

Vuk Vasić
  • 1,398
  • 10
  • 27

3 Answers3

3

How about this? Not tested.

public String toHH24MI(int seconds) {
    int hour = seconds/3600;
    int min = (seconds%3600)/60;
    return String.format("%02d:%02d",hour,min);
}
anonymous
  • 1,317
  • 8
  • 7
  • It is ok :) but it returns 0 instead of 00 for minutes for example. But this is similar enough. I made function and post it below as answer. – Vuk Vasić Mar 27 '14 at 09:52
  • 1
    I can't remember on top of my head the available formats but I thought %2d would print of length 2. I am sure it can be done rather than having to write it yourself. – anonymous Mar 27 '14 at 09:55
  • Ok. Forgot the padding character. Edited answer to use "%02d". – anonymous Mar 27 '14 at 10:03
2

You can use SimpleDateFormat#format() to format a Date into a String in a certain pattern.

String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18
Endrik
  • 2,238
  • 3
  • 19
  • 33
  • I know about that. But the problem is SSSSS format which is 36000 seconds which must be formated into 24:00 time. And i dont have no date to format i only have a integer value of 36000 – Vuk Vasić Mar 27 '14 at 09:33
  • 1
    You might create a Date object from a given time in milliseconds. I.e: Date date = new Date(millis); this way you'll have a date object representing Jan:01:1970 and the given hour. Using the SimpleDateFormatter you can pick up just the hour. To get it in a 24 hours format, you have just to construct the formatter using "kk" instead of "hh": H Hour in day (0-23) Number 0 k Hour in day (1-24) Number 24 K Hour in am/pm (0-11) Number 0 h Hour in am/pm (1-12) Number 12 – Endrik Mar 27 '14 at 09:48
  • 1
    I would recommend using FastDateFormat instead (as it's a fast and thread-safe version of SimpleDateFormat). – Chris311 Mar 27 '14 at 10:08
1

It seems that there is no Java function to do that so i made up my own.

public String getTimeFromSeconds(Integer totalSecs) {
        int hoursi = totalSecs / 3600;
        int minutesi = (totalSecs % 3600) / 60;
        String hours="";
        String minutes = "";
        if( (hoursi > 0 || hoursi == 0) && hoursi < 10)
            hours = "0" + hoursi;
        else 
            hours = String.valueOf(hoursi);

        if( (minutesi > 0 || minutesi==0) && minutesi < 10)
            minutes = "0" + minutesi;  
        else
            minutes = String.valueOf(minutesi);
        return hours + ":" + minutes;
    }
Vuk Vasić
  • 1,398
  • 10
  • 27