001/* 002 * ModeShape (http://www.modeshape.org) 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.modeshape.schematic.document; 017 018import java.util.Date; 019import org.modeshape.schematic.annotation.Immutable; 020 021/** 022 * A {@link Bson.Type#TIMESTAMP timestamp} value for use within a {@link Document BSON object}. <b>Note that using {@link Date} is 023 * recommended for most applications and use cases, as they are more generally suited for representing instants in time.</b> 024 * 025 * @author Randall Hauch <rhauch@redhat.com> (C) 2011 Red Hat Inc. 026 */ 027@Immutable 028public final class Timestamp { 029 030 private final Date time; 031 private final int inc; 032 033 public Timestamp() { 034 this.time = null; 035 this.inc = 0; 036 } 037 038 public Timestamp( Date date ) { 039 this((int)(date.getTime() / 1000L), 0); 040 } 041 042 public Timestamp( int timeInSeconds, 043 int inc ) { 044 this.time = new Date(timeInSeconds * 1000L); 045 this.inc = inc; 046 } 047 048 public int getTime() { 049 return time == null ? 0 : (int)(time.getTime() / 1000L); 050 } 051 052 public int getInc() { 053 return inc; 054 } 055 056 public Date getAsDate() { 057 return new Date(time.getTime()); // make defensive copy 058 } 059 060 @Override 061 public int hashCode() { 062 return getTime(); // note that Date.hashCode() calls Date.getTime(), so our approach works great 063 } 064 065 @Override 066 public boolean equals( Object obj ) { 067 if (obj == this) return true; 068 if (obj instanceof Timestamp) { 069 Timestamp that = (Timestamp)obj; 070 return this.getInc() == that.getInc() && this.getTime() == that.getTime(); 071 } 072 return false; 073 } 074 075 @Override 076 public String toString() { 077 return "TS(" + time + ':' + inc + ')'; 078 } 079}