1 21 22 package org.apache.derby.iapi.util; 23 24 29 public class CheapDateFormatter { 30 static final long SECONDS = 1000L; 31 static final long MINUTES = SECONDS * 60L; 32 static final long HOURS = MINUTES * 60L; 33 static final long DAYS = HOURS * 24L; 34 static final long NORMAL_YEAR = DAYS * 365L; 35 static final long LEAP_YEAR = NORMAL_YEAR + DAYS; 36 static final long FOURYEARS = (NORMAL_YEAR * 3L) + LEAP_YEAR; 37 static final long END_OF_FIRST_YEAR = NORMAL_YEAR; 38 static final long END_OF_SECOND_YEAR = END_OF_FIRST_YEAR + LEAP_YEAR; 39 static final long END_OF_THIRD_YEAR = END_OF_SECOND_YEAR + NORMAL_YEAR; 40 static final int[] DAYS_IN_MONTH = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 41 static final int FEBRUARY = 1; 42 43 62 public static String formatDate(long time) { 63 boolean leapYear = false; 65 66 long year = ((time / FOURYEARS) * 4L); 68 69 long leftover = time % FOURYEARS; 71 time -= (year / 4L) * FOURYEARS; 72 73 year += 1970L; 74 75 if (leftover >= END_OF_FIRST_YEAR) { 77 year++; 78 time -= NORMAL_YEAR; 79 } 80 81 if (leftover >= END_OF_SECOND_YEAR) { 83 year++; 84 time -= NORMAL_YEAR; 85 } 86 87 if (leftover >= END_OF_THIRD_YEAR) { 89 year++; 90 time -= LEAP_YEAR; 91 } 92 93 if ((year % 4L) == 0) { 96 if ((year % 100L) == 0) { 97 if ((year % 400L) == 0) { 98 leapYear = true; 99 } 100 } 101 leapYear = true; 102 } 103 104 long days = (time / DAYS) + 1; 106 107 int month = 1; 109 for (int i = 0; i < DAYS_IN_MONTH.length; i++) { 110 int daysInMonth; 111 112 if (leapYear && (i == FEBRUARY)) { 113 daysInMonth = 29; 115 } else { 116 daysInMonth = DAYS_IN_MONTH[i]; 118 } 119 120 if (days > daysInMonth) { 122 month++; 124 125 days -= daysInMonth; 127 } else { 128 break; 131 } 132 } 133 134 time %= DAYS; 136 137 long hours = time / HOURS; 138 139 time %= HOURS; 141 142 long minutes = time / MINUTES; 143 144 time %= MINUTES; 146 147 long seconds = time / SECONDS; 148 149 time %= SECONDS; 151 152 return year + "-" + 153 twoDigits(month) + "-" + 154 twoDigits(days) + " " + 155 twoDigits(hours) + ":" + 156 twoDigits(minutes) + ":" + 157 twoDigits(seconds) + "." + 158 threeDigits(time) + " GMT"; 159 } 160 161 private static String twoDigits(long val) { 162 String retval; 163 164 if (val < 10) { 165 retval = "0" + val; 166 } else { 167 retval = Long.toString(val); 168 } 169 170 return retval; 171 } 172 173 private static String threeDigits(long val) { 174 String retval; 175 176 if (val < 10) { 177 retval = "00" + val; 178 } else if (val < 100) { 179 retval = "0" + val; 180 } else { 181 retval = Long.toString(val); 182 } 183 184 return retval; 185 } 186 } 187 | Popular Tags |