Util.java Source code

Java tutorial

Introduction

Here is the source code for Util.java

Source

import java.util.Calendar;
import java.util.Date;

public class Util {
    public static String dateToIsoDateTime(String date) {
        StringBuffer sb = new StringBuffer(date);

        if (date.length() >= 8) {
            //20070101 -> 2007-01-01
            //insert hyphens between year, month, and day
            sb.insert(4, '-');
            sb.insert(7, '-');

            //2007-01-01T173012 -> 2007-01-01T17:30:12
            if (date.length() >= 15) {
                //insert colons between hours, minutes, and seconds
                sb.insert(13, ':');
                sb.insert(16, ':');

                //2007-01-01T17:30:12 -> 2007-01-01T17:30:12.000
                //append milliseconds
                if (sb.toString().length() > 19)
                    sb.insert(20, ".000");
                else
                    sb.append(".000");

                //2007-01-01T17:30:12.000 -> 2007-01-01T17:30:12.000Z
                //append UTC indicator if exists
                if (date.length() > 15 && date.charAt(15) == 'Z')
                    sb.append('Z');
            }

            if (sb.length() > 19)
                sb.setLength(19);
        }

        return sb.toString();
    }
}