Source Code Cross Referenced for Timestamp.java in  » JDK-Core » sql » java » sql » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. JDK Core
2. JDK Modules
3. JDK Modules com.sun
4. JDK Modules com.sun.java
5. JDK Modules Platform
6. JDK Modules sun
7. Open Source Build
8. Open Source Graphic Library
9. Open Source IDE Eclipse
10. Open Source J2EE
11. Open Source JDBC Driver
12. Open Source Library
13. Open Source Library Database
14. Open Source Net
15. Open Source Script
16. Science
17. Security
18. Sevlet Container
19. SUN GlassFish
20. Swing Library
21. Web Services apache cxf 2.0.1
22. Web Services AXIS2
23. XML
Microsoft Office Word 2007 Tutorial
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Java Source Code / Java Documentation » JDK Core » sql » java.sql 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * Copyright 1996-2006 Sun Microsystems, Inc.  All Rights Reserved.
003:         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004:         *
005:         * This code is free software; you can redistribute it and/or modify it
006:         * under the terms of the GNU General Public License version 2 only, as
007:         * published by the Free Software Foundation.  Sun designates this
008:         * particular file as subject to the "Classpath" exception as provided
009:         * by Sun in the LICENSE file that accompanied this code.
010:         *
011:         * This code is distributed in the hope that it will be useful, but WITHOUT
012:         * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013:         * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
014:         * version 2 for more details (a copy is included in the LICENSE file that
015:         * accompanied this code).
016:         *
017:         * You should have received a copy of the GNU General Public License version
018:         * 2 along with this work; if not, write to the Free Software Foundation,
019:         * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020:         *
021:         * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022:         * CA 95054 USA or visit www.sun.com if you need additional information or
023:         * have any questions.
024:         */
025:
026:        package java.sql;
027:
028:        import java.util.StringTokenizer;
029:
030:        /**
031:         * <P>A thin wrapper around <code>java.util.Date</code> that allows
032:         * the JDBC API to identify this as an SQL <code>TIMESTAMP</code> value.
033:         * It adds the ability
034:         * to hold the SQL <code>TIMESTAMP</code> fractional seconds value, by allowing
035:         * the specification of fractional seconds to a precision of nanoseconds.
036:         * A Timestamp also provides formatting and
037:         * parsing operations to support the JDBC escape syntax for timestamp values.
038:         *
039:         * <p>The precision of a Timestamp object is calculated to be either:
040:         * <ul>
041:         * <li><code>19 </code>, which is the number of characters in yyyy-mm-dd hh:mm:ss
042:         * <li> <code> 20 + s </code>, which is the number
043:         * of characters in the yyyy-mm-dd hh:mm:ss.[fff...] and <code>s</code> represents  the scale of the given Timestamp,
044:         * its fractional seconds precision.
045:         *</ul>
046:         *
047:         * <P><B>Note:</B> This type is a composite of a <code>java.util.Date</code> and a
048:         * separate nanoseconds value. Only integral seconds are stored in the
049:         * <code>java.util.Date</code> component. The fractional seconds - the nanos - are
050:         * separate.  The <code>Timestamp.equals(Object)</code> method never returns 
051:         * <code>true</code> when passed an object
052:         * that isn't an instance of <code>java.sql.Timestamp</code>, 
053:         * because the nanos component of a date is unknown.
054:         * As a result, the <code>Timestamp.equals(Object)</code>
055:         * method is not symmetric with respect to the
056:         * <code>java.util.Date.equals(Object)</code>
057:         * method.  Also, the <code>hashcode</code> method uses the underlying 
058:         * <code>java.util.Date</code> 
059:         * implementation and therefore does not include nanos in its computation.  
060:         * <P>
061:         * Due to the differences between the <code>Timestamp</code> class
062:         * and the <code>java.util.Date</code>
063:         * class mentioned above, it is recommended that code not view
064:         * <code>Timestamp</code> values generically as an instance of
065:         * <code>java.util.Date</code>.  The
066:         * inheritance relationship between <code>Timestamp</code>
067:         * and <code>java.util.Date</code> really 
068:         * denotes implementation inheritance, and not type inheritance.  
069:         */
070:        public class Timestamp extends java.util.Date {
071:
072:            /**
073:             * Constructs a <code>Timestamp</code> object initialized
074:             * with the given values.
075:             *
076:             * @param year the year minus 1900
077:             * @param month 0 to 11 
078:             * @param date 1 to 31
079:             * @param hour 0 to 23
080:             * @param minute 0 to 59
081:             * @param second 0 to 59
082:             * @param nano 0 to 999,999,999
083:             * @deprecated instead use the constructor <code>Timestamp(long millis)</code>
084:             * @exception IllegalArgumentException if the nano argument is out of bounds
085:             */
086:            @Deprecated
087:            public Timestamp(int year, int month, int date, int hour,
088:                    int minute, int second, int nano) {
089:                super (year, month, date, hour, minute, second);
090:                if (nano > 999999999 || nano < 0) {
091:                    throw new IllegalArgumentException(
092:                            "nanos > 999999999 or < 0");
093:                }
094:                nanos = nano;
095:            }
096:
097:            /**
098:             * Constructs a <code>Timestamp</code> object 
099:             * using a milliseconds time value. The
100:             * integral seconds are stored in the underlying date value; the
101:             * fractional seconds are stored in the <code>nanos</code> field of
102:             * the <code>Timestamp</code> object.
103:             *
104:             * @param time milliseconds since January 1, 1970, 00:00:00 GMT.
105:             *        A negative number is the number of milliseconds before
106:             *         January 1, 1970, 00:00:00 GMT.
107:             * @see java.util.Calendar 
108:             */
109:            public Timestamp(long time) {
110:                super ((time / 1000) * 1000);
111:                nanos = (int) ((time % 1000) * 1000000);
112:                if (nanos < 0) {
113:                    nanos = 1000000000 + nanos;
114:                    super .setTime(((time / 1000) - 1) * 1000);
115:                }
116:            }
117:
118:            /**
119:             * Sets this <code>Timestamp</code> object to represent a point in time that is 
120:             * <tt>time</tt> milliseconds after January 1, 1970 00:00:00 GMT. 
121:             *
122:             * @param time   the number of milliseconds.
123:             * @see #getTime
124:             * @see #Timestamp(long time)
125:             * @see java.util.Calendar
126:             */
127:            public void setTime(long time) {
128:                super .setTime((time / 1000) * 1000);
129:                nanos = (int) ((time % 1000) * 1000000);
130:                if (nanos < 0) {
131:                    nanos = 1000000000 + nanos;
132:                    super .setTime(((time / 1000) - 1) * 1000);
133:                }
134:            }
135:
136:            /**
137:             * Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
138:             * represented by this <code>Timestamp</code> object.
139:             *
140:             * @return  the number of milliseconds since January 1, 1970, 00:00:00 GMT
141:             *          represented by this date.
142:             * @see #setTime
143:             */
144:            public long getTime() {
145:                long time = super .getTime();
146:                return (time + (nanos / 1000000));
147:            }
148:
149:            /**
150:             * @serial
151:             */
152:            private int nanos;
153:
154:            /**
155:             * Converts a <code>String</code> object in JDBC timestamp escape format to a
156:             * <code>Timestamp</code> value.
157:             *
158:             * @param s timestamp in format <code>yyyy-mm-dd hh:mm:ss[.f...]</code>.  The
159:             * fractional seconds may be omitted.
160:             * @return corresponding <code>Timestamp</code> value
161:             * @exception java.lang.IllegalArgumentException if the given argument
162:             * does not have the format <code>yyyy-mm-dd hh:mm:ss[.f...]</code>
163:             */
164:            public static Timestamp valueOf(String s) {
165:                String date_s;
166:                String time_s;
167:                String nanos_s;
168:                int year;
169:                int month;
170:                int day;
171:                int hour;
172:                int minute;
173:                int second;
174:                int a_nanos = 0;
175:                int firstDash;
176:                int secondDash;
177:                int dividingSpace;
178:                int firstColon = 0;
179:                int secondColon = 0;
180:                int period = 0;
181:                String formatError = "Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]";
182:                String zeros = "000000000";
183:                String delimiterDate = "-";
184:                String delimiterTime = ":";
185:                StringTokenizer stringTokeninzerDate;
186:                StringTokenizer stringTokeninzerTime;
187:
188:                if (s == null)
189:                    throw new java.lang.IllegalArgumentException("null string");
190:
191:                int counterD = 0;
192:                int intDate[] = { 4, 2, 2 };
193:
194:                int counterT = 0;
195:                int intTime[] = { 2, 2, 12 };
196:
197:                // Split the string into date and time components
198:                s = s.trim();
199:                dividingSpace = s.indexOf(' ');
200:                if (dividingSpace > 0) {
201:                    date_s = s.substring(0, dividingSpace);
202:                    time_s = s.substring(dividingSpace + 1);
203:                } else {
204:                    throw new java.lang.IllegalArgumentException(formatError);
205:                }
206:
207:                stringTokeninzerTime = new StringTokenizer(time_s,
208:                        delimiterTime);
209:                stringTokeninzerDate = new StringTokenizer(date_s,
210:                        delimiterDate);
211:
212:                while (stringTokeninzerDate.hasMoreTokens()) {
213:                    String tokenDate = stringTokeninzerDate.nextToken();
214:                    if (tokenDate.length() != intDate[counterD]) {
215:                        throw new java.lang.IllegalArgumentException(
216:                                formatError);
217:                    }
218:                    counterD++;
219:                }
220:
221:                /*
222:                     //Commenting this portion out for checking of time
223:
224:                while(stringTokeninzerTime.hasMoreTokens()) {
225:                     String tokenTime = stringTokeninzerTime.nextToken();
226:                
227:                     if	(counterT < 2 && tokenTime.length() != intTime[counterT]  ) {
228:                	throw new java.lang.IllegalArgumentException(formatError);
229:                     }
230:                     counterT++;	
231:                }	     
232:                 */
233:
234:                // Parse the date
235:                firstDash = date_s.indexOf('-');
236:                secondDash = date_s.indexOf('-', firstDash + 1);
237:
238:                // Parse the time
239:                if (time_s == null)
240:                    throw new java.lang.IllegalArgumentException(formatError);
241:                firstColon = time_s.indexOf(':');
242:                secondColon = time_s.indexOf(':', firstColon + 1);
243:                period = time_s.indexOf('.', secondColon + 1);
244:
245:                // Convert the date
246:                if ((firstDash > 0) && (secondDash > 0)
247:                        && (secondDash < date_s.length() - 1)) {
248:                    year = Integer.parseInt(date_s.substring(0, firstDash)) - 1900;
249:                    month = Integer.parseInt(date_s.substring(firstDash + 1,
250:                            secondDash)) - 1;
251:                    day = Integer.parseInt(date_s.substring(secondDash + 1));
252:                } else {
253:                    throw new java.lang.IllegalArgumentException(formatError);
254:                }
255:
256:                // Convert the time; default missing nanos
257:                if ((firstColon > 0) & (secondColon > 0)
258:                        & (secondColon < time_s.length() - 1)) {
259:                    hour = Integer.parseInt(time_s.substring(0, firstColon));
260:                    minute = Integer.parseInt(time_s.substring(firstColon + 1,
261:                            secondColon));
262:                    if ((period > 0) & (period < time_s.length() - 1)) {
263:                        second = Integer.parseInt(time_s.substring(
264:                                secondColon + 1, period));
265:                        nanos_s = time_s.substring(period + 1);
266:                        if (nanos_s.length() > 9)
267:                            throw new java.lang.IllegalArgumentException(
268:                                    formatError);
269:                        if (!Character.isDigit(nanos_s.charAt(0)))
270:                            throw new java.lang.IllegalArgumentException(
271:                                    formatError);
272:                        nanos_s = nanos_s
273:                                + zeros.substring(0, 9 - nanos_s.length());
274:                        a_nanos = Integer.parseInt(nanos_s);
275:                    } else if (period > 0) {
276:                        throw new java.lang.IllegalArgumentException(
277:                                formatError);
278:                    } else {
279:                        second = Integer.parseInt(time_s
280:                                .substring(secondColon + 1));
281:                    }
282:                } else {
283:                    throw new java.lang.IllegalArgumentException();
284:                }
285:
286:                return new Timestamp(year, month, day, hour, minute, second,
287:                        a_nanos);
288:            }
289:
290:            /**
291:             * Formats a timestamp in JDBC timestamp escape format.
292:             *         <code>yyyy-mm-dd hh:mm:ss.fffffffff</code>,
293:             * where <code>ffffffffff</code> indicates nanoseconds.
294:             * <P>
295:             * @return a <code>String</code> object in
296:             *           <code>yyyy-mm-dd hh:mm:ss.fffffffff</code> format
297:             */
298:            public String toString() {
299:
300:                int year = super .getYear() + 1900;
301:                int month = super .getMonth() + 1;
302:                int day = super .getDate();
303:                int hour = super .getHours();
304:                int minute = super .getMinutes();
305:                int second = super .getSeconds();
306:                String yearString;
307:                String monthString;
308:                String dayString;
309:                String hourString;
310:                String minuteString;
311:                String secondString;
312:                String nanosString;
313:                String zeros = "000000000";
314:                String yearZeros = "0000";
315:                StringBuffer timestampBuf;
316:
317:                if (year < 1000) {
318:                    // Add leading zeros 
319:                    yearString = "" + year;
320:                    yearString = yearZeros.substring(0, (4 - yearString
321:                            .length()))
322:                            + yearString;
323:                } else {
324:                    yearString = "" + year;
325:                }
326:                if (month < 10) {
327:                    monthString = "0" + month;
328:                } else {
329:                    monthString = Integer.toString(month);
330:                }
331:                if (day < 10) {
332:                    dayString = "0" + day;
333:                } else {
334:                    dayString = Integer.toString(day);
335:                }
336:                if (hour < 10) {
337:                    hourString = "0" + hour;
338:                } else {
339:                    hourString = Integer.toString(hour);
340:                }
341:                if (minute < 10) {
342:                    minuteString = "0" + minute;
343:                } else {
344:                    minuteString = Integer.toString(minute);
345:                }
346:                if (second < 10) {
347:                    secondString = "0" + second;
348:                } else {
349:                    secondString = Integer.toString(second);
350:                }
351:                if (nanos == 0) {
352:                    nanosString = "0";
353:                } else {
354:                    nanosString = Integer.toString(nanos);
355:
356:                    // Add leading zeros
357:                    nanosString = zeros
358:                            .substring(0, (9 - nanosString.length()))
359:                            + nanosString;
360:
361:                    // Truncate trailing zeros
362:                    char[] nanosChar = new char[nanosString.length()];
363:                    nanosString.getChars(0, nanosString.length(), nanosChar, 0);
364:                    int truncIndex = 8;
365:                    while (nanosChar[truncIndex] == '0') {
366:                        truncIndex--;
367:                    }
368:
369:                    nanosString = new String(nanosChar, 0, truncIndex + 1);
370:                }
371:
372:                // do a string buffer here instead.
373:                timestampBuf = new StringBuffer(20 + nanosString.length());
374:                timestampBuf.append(yearString);
375:                timestampBuf.append("-");
376:                timestampBuf.append(monthString);
377:                timestampBuf.append("-");
378:                timestampBuf.append(dayString);
379:                timestampBuf.append(" ");
380:                timestampBuf.append(hourString);
381:                timestampBuf.append(":");
382:                timestampBuf.append(minuteString);
383:                timestampBuf.append(":");
384:                timestampBuf.append(secondString);
385:                timestampBuf.append(".");
386:                timestampBuf.append(nanosString);
387:
388:                return (timestampBuf.toString());
389:            }
390:
391:            /**
392:             * Gets this <code>Timestamp</code> object's <code>nanos</code> value.
393:             *
394:             * @return this <code>Timestamp</code> object's fractional seconds component
395:             * @see #setNanos
396:             */
397:            public int getNanos() {
398:                return nanos;
399:            }
400:
401:            /**
402:             * Sets this <code>Timestamp</code> object's <code>nanos</code> field
403:             * to the given value.
404:             *
405:             * @param n the new fractional seconds component
406:             * @exception java.lang.IllegalArgumentException if the given argument
407:             *            is greater than 999999999 or less than 0
408:             * @see #getNanos
409:             */
410:            public void setNanos(int n) {
411:                if (n > 999999999 || n < 0) {
412:                    throw new IllegalArgumentException(
413:                            "nanos > 999999999 or < 0");
414:                }
415:                nanos = n;
416:            }
417:
418:            /**
419:             * Tests to see if this <code>Timestamp</code> object is
420:             * equal to the given <code>Timestamp</code> object.
421:             *
422:             * @param ts the <code>Timestamp</code> value to compare with
423:             * @return <code>true</code> if the given <code>Timestamp</code>
424:             *         object is equal to this <code>Timestamp</code> object;
425:             *         <code>false</code> otherwise
426:             */
427:            public boolean equals(Timestamp ts) {
428:                if (super .equals(ts)) {
429:                    if (nanos == ts.nanos) {
430:                        return true;
431:                    } else {
432:                        return false;
433:                    }
434:                } else {
435:                    return false;
436:                }
437:            }
438:
439:            /**
440:             * Tests to see if this <code>Timestamp</code> object is
441:             * equal to the given object.
442:             *
443:             * This version of the method <code>equals</code> has been added
444:             * to fix the incorrect 
445:             * signature of <code>Timestamp.equals(Timestamp)</code> and to preserve backward 
446:             * compatibility with existing class files.
447:             *
448:             * Note: This method is not symmetric with respect to the 
449:             * <code>equals(Object)</code> method in the base class.
450:             *
451:             * @param ts the <code>Object</code> value to compare with
452:             * @return <code>true</code> if the given <code>Object</code> is an instance
453:             *         of a <code>Timestamp</code> that
454:             *         is equal to this <code>Timestamp</code> object;
455:             *         <code>false</code> otherwise
456:             */
457:            public boolean equals(java.lang.Object ts) {
458:                if (ts instanceof  Timestamp) {
459:                    return this .equals((Timestamp) ts);
460:                } else {
461:                    return false;
462:                }
463:            }
464:
465:            /**
466:             * Indicates whether this <code>Timestamp</code> object is
467:             * earlier than the given <code>Timestamp</code> object.
468:             *
469:             * @param ts the <code>Timestamp</code> value to compare with
470:             * @return <code>true</code> if this <code>Timestamp</code> object is earlier;
471:             *        <code>false</code> otherwise
472:             */
473:            public boolean before(Timestamp ts) {
474:                return compareTo(ts) < 0;
475:            }
476:
477:            /**
478:             * Indicates whether this <code>Timestamp</code> object is
479:             * later than the given <code>Timestamp</code> object.
480:             *
481:             * @param ts the <code>Timestamp</code> value to compare with
482:             * @return <code>true</code> if this <code>Timestamp</code> object is later;
483:             *        <code>false</code> otherwise
484:             */
485:            public boolean after(Timestamp ts) {
486:                return compareTo(ts) > 0;
487:            }
488:
489:            /**
490:             * Compares this <code>Timestamp</code> object to the given 
491:             * <code>Timestamp</code> object.
492:             *
493:             * @param   ts   the <code>Timestamp</code> object to be compared to
494:             *                this <code>Timestamp</code> object
495:             * @return  the value <code>0</code> if the two <code>Timestamp</code>
496:             *          objects are equal; a value less than <code>0</code> if this 
497:             *          <code>Timestamp</code> object is before the given argument;
498:             *          and a value greater than <code>0</code> if this 
499:             *          <code>Timestamp</code> object is after the given argument.
500:             * @since   1.4
501:             */
502:            public int compareTo(Timestamp ts) {
503:                int i = super .compareTo(ts);
504:                if (i == 0) {
505:                    if (nanos > ts.nanos) {
506:                        return 1;
507:                    } else if (nanos < ts.nanos) {
508:                        return -1;
509:                    }
510:                }
511:                return i;
512:
513:            }
514:
515:            /**
516:             * Compares this <code>Timestamp</code> object to the given 
517:             * <code>Date</code>, which must be a <code>Timestamp</code>
518:             * object. If the argument is not a <code>Timestamp</code> object,
519:             * this method throws a <code>ClassCastException</code> object.
520:             * (<code>Timestamp</code> objects are 
521:             * comparable only to other <code>Timestamp</code> objects.)
522:             *
523:             * @param o the <code>Date</code> to be compared, which must be a
524:             *        <code>Timestamp</code> object
525:             * @return  the value <code>0</code> if this <code>Timestamp</code> object
526:             *          and the given object are equal; a value less than <code>0</code> 
527:             *          if this  <code>Timestamp</code> object is before the given argument;
528:             *          and a value greater than <code>0</code> if this 
529:             *          <code>Timestamp</code> object is after the given argument.
530:             *
531:             * @since	1.5
532:             */
533:            public int compareTo(java.util.Date o) {
534:                if (o instanceof  Timestamp) {
535:                    // When Timestamp instance compare it with a Timestamp
536:                    // Hence it is basically calling this.compareTo((Timestamp))o);
537:                    // Note typecasting is safe because o is instance of Timestamp
538:                    return compareTo((Timestamp) o);
539:                } else {
540:                    // When Date doing a o.compareTo(this)
541:                    // will give wrong results.
542:                    Timestamp ts = new Timestamp(o.getTime());
543:                    return this .compareTo(ts);
544:                }
545:            }
546:
547:            static final long serialVersionUID = 2745179027874758501L;
548:
549:        }
w_w_w.___j__a__v___a__2___s___.__c_o__m__ | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.