⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 datetime.java

📁 一个用java写的地震分析软件(无源码)
💻 JAVA
字号:
package org.trinet.util;

import java.text.*;
import java.util.*;
import org.trinet.jdbc.datatypes.DateStringFormatter;

/**
 * Handle Epoch date/time in a reasonable fashion
 * Extends the Date class.
 * Added functions:
    1) will return seconds as a double with a fractional part,
    2) provides a simple toString method
    3) provides a julian second constructor
    4) provides constructors like those that were depricated
    5) allows setting of toString format using SimpleDateFormat pattern syntax
 */

/*  JAVA notes:
    The Java epoch start time is : Jan. 1, 1970, 00:00 GMT
    The Date class is based on UTC (GMT) and doesn't deal with time zones.<p>

    In v1.1 Sun created a Calendar class to aid "internationalization" and
    deal with time zones. They depricated the Date constructors that used
    calendar time because which assumed everything was GMT and didn't handle
    time zone conversions. The Calendar class and the use of "locales"
    complicated things alot and solved problems we didn't really care about.<p>

    NOTE: THE PRECISION OF THE JAVA DATE AND CALENDAR CLASSES ARE LIMITED MILLISECS<p>

    Month integers follow DATE: January=0, February=2...
*/
/* Deprecation Note:

    Deprecation warnings should be ignored.
    This class defines methods that have the same
    names as methods deprecated in Date. This generates the warnings.
*/

public class DateTime extends Date
       implements org.trinet.jdbc.datatypes.DateStringFormatter
{

    TimeZone gmt = TimeZone.getTimeZone("GMT");	    // all internal work in GMT
    public GregorianCalendar calendar = new GregorianCalendar(gmt);

    /** The default format string. NOTE: the "S" format returns milliseconds
     * as an integer. This is prone to unexpected formatting results.
     * For example, if the seconds part of a time = 12.03456. the "ss.SS" format returns "12.34" and
     * "ss.SSSS" reuturns "12.0034". Only "ss.SSS" gives a correct result. */
    //static String fmtString = "MMMM dd, yyyy HH:mm:ss.SSSS";
    static String fmtString = "MMMM dd, yyyy HH:mm:ss.SSS";

    /** The difference between the fractional part of seconds as stored in the millis
    precision of the Calendar and the actual value. It is added to the epoch to achieve
    the desired precision. */
//    double fracDiff = 0.0;    // 0.0 means the precision is only to milliseconds
    long extraNanos = 0;    // 0 means the precision is only to milliseconds
/*

IMPORTANT: if you use a string with two decimal places in sec the parser
      screws up!
Current systemTime: October 21, 1999 22:39:55.379
Parse test of string: October 21, 1999 22:39:55.379
Parse result is     : October 21, 1999 22:39:55.379 <-- good parse
Current systemTime: October 21, 1999 22:39:55.37
Parse test of string: October 21, 1999 22:39:55.37
Parse result is     : October 21, 1999 22:39:55.03  <-- bad parse
*/

// Date string example: "January 26, 1999 10:41:04 PM GMT"
    //    DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);

// NOTE:
// We must override ALL of Date's constructors. If we don't a caller could instatiate
// a DateTime object using the parent constructor and not set the Calendar object
// used in this class

/**
 * Create DateTime object with current time
 */
public DateTime ()
{
    super();
    calendar.setTime(this);	    // keep the calendar object current
}

/**
 * Create DateTime Date object
 */
public DateTime (Date date)
{
    super(date.getTime());
    calendar.setTime(this);	    // keep the calendar object current

    setTime(this);
}

/**
 * Create DateTime object with current time
 */
public DateTime (double jsec)
{
/*
    super ( (long) (jsec * 1000.0) );	    // millisec since epoch parent construtor
    calendar.setTime(this);	    // keep the calendar object current

    // keep additional precision beyond milliseconds
    fracDiff = jsec - getEpochSeconds();
*/

  setTime(jsec);
}

/**
 * Create DateTime object with the given time. Time is assumed to be GMT. Year is
 * 4 digits. E.g. 1998 NOT "98". Month follows weird Java convention of January = 0.
 * Note that range overflows are allowed. E.g. day 32 of January would be interpreted
 * as February 1. Precision is 0.001 sec.
 */
public DateTime(int year,
            int month,
            int day,
            int hr,
            int mn,
	    double sec)
{

  setTime(year, month, day, hr, mn, sec );

}

/**
 * Parse a string using the specified time format and return a DateTime object.
 * Sets the instance default date String format to the specified format.
 */

public DateTime(String str, String fmtString)
{
    setTime (EpochTime.stringToEpoch(str, fmtString));
    setFormat(fmtString);
}

/**
 * Parse a string in standard date/time format and return a DateTime object.
 * Standard format Example: "October 20, 1999 22:10:25.00". GMT is assumed.
 */

public DateTime(String str)
{
    double dt = EpochTime.stringToEpoch(str, fmtString);

    setTime (dt);
}

/** Return the fractional part of the second.  */
public static double fracOf (double sec) {
   return sec - ((int) sec);
}

public void setTime(int year,
            int month,
            int day,
            int hr,
            int mn,
	    double sec)
{
    // use calendar object to "parse" date/time info
    calendar.set(year, month, day, hr, mn, (int) sec );

// get milliseconds part of the seconds. You must set this seperately because there is no set()
// command in the Calendar class with millisecond precision. If you don't set it you "inherit"
// the milliseconds that were stuffed in at the time it was instantiated.

    int mills = (int) ((sec - ((int)sec)) * 1000);
    calendar.set(Calendar.MILLISECOND, mills);

    // this weirdness is because you can't get epoch milliseconds directly from a Calender
    // object. Calendar.getTime() returns a Date, then Date.getTime() returns millis
    setTime(calendar.getTime().getTime() );

    // keep additional precision beyond milliseconds
    extraNanos = getExtraNanos(sec);
}

protected long getExtraNanos(double sec) {

    int mills = (int) ((sec - (int) sec) * 1000.0);
    // the round is necessary because of twos-compliment precision issues
    // 0.6089 turns into 0.6088999999

    long nanos = (long) Math.round((sec - (int) sec) * 1000000.0);

    return nanos - mills * 1000;
}

/**
 * Set time using seconds past epoch.
 */
public void setTime (double jsec)
{
    super.setTime ( (long) (jsec * 1000.0) );	    // millisec since epoch
    calendar.setTime(this);	    // keep the calendar object current

    // keep additional precision beyond milliseconds
    extraNanos = getExtraNanos(jsec);
}
/**
 * Set time using milliseconds past epoch.
 */
public void setTime (long millis)
{
    setTime ((double)millis / 1000.0);
}

/**
 * Set time using Date object.
 */
public void setTime (Date date)
{
    setTime( date.getTime() ); // millisec since epoch
}

/**
 * Set the date/time format returned by toString as a
 * SimpleDateFormat pattern string. Default is:  "MMMM dd, yyyy HH:mm:ss.SSSS"
 * @see: java.text.SimpleDateFormat
 */
public void setFormat (String formatString)
{
    fmtString = formatString;
}

/**
 * Return DateTime as string as native GMT
 */
public String toString()
{
    return toDateString(null );
}

/**
 * Return DateTime formatted as specified in pattern string native GMT
 */
public String toDateString(String pattern)
{
    return EpochTime.dateToString(this, pattern);
}

/**
 * Return DateTime as string as native GMT
 */
public static String toString(double secs, String fmtStr)
{
    return EpochTime.epochToString(secs, fmtStr );
}


/** Trim the trailing places of a double to nanoseconds 10^-6. This is useful
* when precision jitter in double arithmetic causes extraneous digits. For example:
0.01 * 301 = 3.0100000000000002 */
     public static double trimToNanos(double val) {

            long intVal = Math.round(val * 1000000.0);
            return (double) intVal / 1000000.0;
     }
     /** Returns 'true' id the two doubles are "equal" down to the 6th decimal place
     (nanoseconds). The decimal place is positive number
     Calculated values of epoch seconds will not always be exactly equal numerically
     because precision jitter in double arithmetic causes extraneous digits.
     For example: 0.01 * 301 = 3.0100000000000002
     */
     public static boolean areEqual(double d1, double d2) {
            return areEqual(d1, d2, 6);
     }

     /** Returns 'true' id the two doubles are "equal" within the to the nth decimal place.
     The decimal place is positive number
     Calculated values of epoch seconds will not always be exactly equal numerically
     because precision jitter in double arithmetic causes extraneous digits.
     For example: 0.01 * 301 = 3.0100000000000002
     */
     public static boolean areEqual(double d1, double d2, int decimalPlace) {

            double diff = Math.abs(d1 - d2);
            return (diff < Math.pow(10, -(decimalPlace+1)));
     }
/**
 * Return DateTime as string converted to local time (PST, etc.)
 */
/*
public String toLocalString()
{
    fmt.setTimeZone(TimeZone.getDefault());	// set to local timezone

    return  fmt.format(this);
}
*/

/**
 *
 */
    public double getEpochSeconds()
    {
       double epoch = (double) calendar.getTime().getTime() / 1000.0;
       epoch += (double) extraNanos/1000000.0;
       return epoch;
    }

    public long getMilliSeconds()
    {
	return  calendar.getTime().getTime();
    }

    public int getYear()
    {
	return calendar.get(Calendar.YEAR);
    }
    public int getMonth()	// January = 0
    {
	return calendar.get(Calendar.MONTH);
    }
    public int getDay()
    {
	return calendar.get(Calendar.DAY_OF_MONTH);
    }
    public int getHour()
    {
	return calendar.get(Calendar.HOUR_OF_DAY);  // 0 -> 23
    }
    public int getMinute()
    {
	return calendar.get(Calendar.MINUTE);
    }
    public int getSecond()
    {
	return calendar.get(Calendar.SECOND);
    }
    /** Includes fractional part to nano-second accuracy. */
    public double getDoubleSecond()
    {
      double sec = (double) calendar.get(Calendar.SECOND);
      sec += (double) calendar.get(Calendar.MILLISECOND) / 1000.0;
      sec += (double) extraNanos / 1000000.0;
	 return sec;
    }

    /** Return a string for the seconds with the given precision. for example: if seconds
     * equals 2.01450 then getSecondsStringToPre(0) = "02" and
     * getSecondsStringToPre(3) = "02.045"*/
    public String getSecondsStringToPrecisionOf (int decimalPlaces) {

      int pre = 3;
      if (decimalPlaces < 1) pre = 2;
      // show leading zeros
      String fmtStr= "%0"+(pre+decimalPlaces)+"."+decimalPlaces+"f";
        Format fmt = new Format(fmtStr);
        return fmt.form(this.getDoubleSecond());
    }

/** Return the epoch seconds of the START of the year of this time. */
    public double getStartOfYear () {
       return (new DateTime(getYear(), 0, 0, 0, 0, 0.0)).getEpochSeconds();
    }
/** Return the epoch seconds of the START of the month of this time. */
    public double getStartOfMonth () {
       return (new DateTime(getYear(), getMonth(), 0, 0, 0, 0.0)).getEpochSeconds();
    }
/** Return the epoch seconds of the START of the day of this time. */
    public double getStartOfDay () {
       return (new DateTime(getYear(), getMonth(), getDay(), 0, 0, 0.0)).getEpochSeconds();
    }
/** Return the epoch seconds of the START of the hour of this time. */
    public double getStartOfHour () {
       return (new DateTime(getYear(), getMonth(), getDay(), getHour(), 0, 0.0)).getEpochSeconds();
    }
/** Return the epoch seconds of the START of the minute of this time. */
    public double getStartOfMinute () {
       return (new DateTime(getYear(), getMonth(), getDay(), getHour(), getMinute(), 0.0)).getEpochSeconds();
    }

/**
 * Main for testing.
 * Interprets command-line arg as epoch seconds and reports in default format.
 * If no arg reports current time.
 */
    public static void main (String args[])
    {
	DateTime dtime = new DateTime();    // sets dtime to current time

	if (args.length > 0)	// translate epoch second on command-line value
	{
	  Double val = Double.valueOf(args[0]);	    // convert arg String to 'double'
	  double sec = (double) val.doubleValue();

	  dtime.setTime(sec);	    // set time to epoch sec given by arg
	}

	System.out.println ("Epoch seconds =\t" + dtime.getEpochSeconds() +
			    " (" + (long) dtime.getEpochSeconds() + ")");
	System.out.println ( dtime.toString() );
//      	System.out.println ( dtime.toLocalString() );

//	DateTime dt = new DateTime(dtime.toString());
	//	System.out.println ( "parse test: " + dt.toString()) ;

     double epoch = 967896022.123456;   // 2000/09/02 12:00:22.123456

     DateTime etime = new DateTime(epoch);
     System.out.println (" Epoch test: "+ etime.getEpochSeconds() + " -> "+
                                 etime.toString() + " sec= "+etime.getDoubleSecond());

     etime.setTime(967896022.123456);
     System.out.println (" Epoch test: "+ etime.getEpochSeconds() + " -> "+
                                 etime.toString() + " sec= "+etime.getDoubleSecond() );

     etime.setTime(2000, 9-1, 2, 12, 0, 22.123456);
     System.out.println (" Epoch test: "+ etime.getEpochSeconds() + " -> "+
                                 etime.toString() + " sec= "+etime.getDoubleSecond());

     etime.setTime((long) (967896022 * 1000.0));
     System.out.println (" Epoch test: "+ etime.getEpochSeconds() + " -> "+
                                 etime.toString() + " sec= "+etime.getDoubleSecond());

     etime.setTime((long) (0.0123 * 1000.0));
     System.out.println (" Epoch test: "+ etime.getEpochSeconds() + " -> "+
                                 etime.toString() + " sec= "+etime.getDoubleSecond());

     System.out.println (" Precision test ");
     etime = new DateTime(2.0145);
     for (int i=0; i<6; i++) {
       System.out.println (i + "  "+ etime.getSecondsStringToPrecisionOf(i));
     }
   }	// end of main

} // end of class

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -