Search code examples
javadatetimesimpledateformatdatetime-formatgregorian-calendar

Conditional time formatting Java


I'm trying to use Javas GregorianCalendar and SimpleDateFormatclasses to create Time Series.

The raw data that I'm using is in simple epoch format (Unix time) and I translate all of these timestamps into readable time and dates.

However, If I have a time series that range from say 23.00 to 01.00 (i.e the date changes somewhere in the middle) I would like my output to reflect that.

Example:

{"23.00", "23.30", "00.00 2015-08-12", "00.30", "01.00"}

Do you know if there is some support for this in SimpleDateFormat, or anything I can do to automate this process?

Thanks!


Solution

  • Here's some sample code to work with. The key bits are using the Calendar class to track changes in the date. This outputs:

    {"23.00", "23.30", "00.00 2015-08-12", "00.30", "01.00", "01.30"}
    

    Code:

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    
    public class TS {
    
        // 11PM 2015-08-12
        long base=1439348420L; 
    
        long[] timestamps = {
            base,
            base + 1800,
            base + 1800*2,
            base + 1800*3,
            base + 1800*4,
            base + 1800*5
        };
    
        // MAKE SURE THIS IS IN THE RIGHT TIMEZONE
        Calendar cal = Calendar.getInstance();
        int lastday;
        static DateFormat HHMM = new SimpleDateFormat("\"HH.mm\"");
        static DateFormat DATE_HHMM = new SimpleDateFormat("\"HH.mm yyyy-MM-dd\"");
    
        public void run() {
            StringBuilder sb = new StringBuilder("{");
            for (int i=0; i<timestamps.length; i++) {
                if (i>0) sb.append(", ");
                sb.append(formattedDate(timestamps[i]));
            }
            sb.append('}');
            System.out.println(sb.toString());
        }
    
        public String formattedDate(long unixtime) {
            String result = null;
            cal.setTimeInMillis(unixtime*1000);
    
            int today = cal.get(Calendar.DAY_OF_MONTH);
            if (today != lastday && lastday > 0) {
                result = DATE_HHMM.format(cal.getTime());
            } else {
                result =  HHMM.format(cal.getTime());
            }
            lastday = today;
            return result;
        }
    
        public static void main(String[] args) {
            TS ts = new TS();
            ts.run();
        }
    
    }