1 16 17 package tutorial; 18 19 import java.util.Date ; 20 21 28 public class RfcDateFormat { 29 30 33 private static final String [] WEEKDAYS = 34 {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; 35 38 private static final String [] MONTHS = 39 {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; 40 41 49 public static String format(Date date) { 50 51 long s = date.getTime();; 53 if (s >= 0) { 54 s /= 1000; 56 } else { 57 s = (s - 999) / 1000; 59 } 60 61 int dn = (int) (s / 86400); 62 s %= 86400; if (s < 0) { 64 s += 86400; 65 dn--; 66 } 67 dn += 1969 * 365 + 492 - 19 + 4; 69 int y = 400 * (dn / 146097) + 1; 71 int d = dn % 146097; 72 if (d == 146096) { 73 y += 399; 75 d = 365; 76 } else { 77 y += 100 * (d / 36524); 78 d %= 36524; 79 y += 4 * (d / 1461); 80 d %= 1461; 81 if (d == 1460) { 82 y += 3; 84 d = 365; 85 } else { 86 y += d / 365; 87 d %= 365; 88 } 89 } 90 91 boolean isleap = ((y % 4 == 0) && !(y % 100 == 0)) || (y % 400 == 0); 92 93 if (!isleap && (d >= 59)) { 95 d++; 97 } 98 if (d >= 60) { 99 d++; 101 } 102 int mon = ((d % 214) / 61) * 2 + ((d % 214) % 61) / 31; 103 if (d > 213) { 104 mon += 7; 105 } 106 d = ((d % 214) % 61) % 31 + 1; 107 108 int m = (int) (s / 60); 110 int h = m / 60; 111 m %= 60; 112 s %= 60; 113 114 int w = (dn + 1) % 7; 116 117 118 StringBuffer buff = new StringBuffer (32); 119 buff.append(WEEKDAYS[w]); 120 buff.append(", "); 121 buff.append((char) (d / 10 + '0')); 122 buff.append((char) (d % 10 + '0')); 123 buff.append(' '); 124 buff.append(MONTHS[mon]); 125 buff.append(' '); 126 buff.append(y); 127 buff.append(' '); 128 buff.append((char) (h / 10 + '0')); 129 buff.append((char) (h % 10 + '0')); 130 buff.append(':'); 131 buff.append((char) (m / 10 + '0')); 132 buff.append((char) (m % 10 + '0')); 133 buff.append(':'); 134 buff.append((char) (s / 10 + '0')); 135 buff.append((char) (s % 10 + '0')); 136 buff.append(" GMT"); 137 return buff.toString(); 138 } 139 } 140 | Popular Tags |