Package test;
Import java. SQL. timestamp;
Import java. Text. parseexception;
Import java. Text. simpledateformat;
Import java. util. date;
/**
* Timestamp and String Conversion
* @ Author Administrator
*
*/
Public class dateutil {
/**
* Default date format
*/
Private Static final string default_format = "yyyy-mm-dd hh: mm: Ss. SSS "; // timestamp format must be yyyy-mm-dd hh: mm: ss [. fffffffff]
/**
* Default constructor
*/
Private dateutil (){
}
/**
* If the conversion format of string to date is null, the default format is used for conversion.
* @ Param STR string
* @ Param Format: Date Format
* @ Return date
* @ Throws java. Text. parseexception
*/
Public static date str2date (string STR, string format ){
If (null = STR | "". Equals (STR )){
Return NULL;
}
// If the String Conversion format is not specified, the conversion is performed in the default format.
If (null = format | "". Equals (Format )){
Format = default_format;
}
Simpledateformat SDF = new simpledateformat (format );
Date = NULL;
Try {
Date = SDF. parse (STR );
Return date;
} Catch (parseexception e ){
E. printstacktrace ();
}
Return NULL;
}
/** Convert a date to a string
* @ Param date
* @ Param Format: Date Format
* @ Return string
*/
Public static string date2str (date, string format ){
If (null = Date ){
Return NULL;
}
Simpledateformat SDF = new simpledateformat (format );
Return SDF. Format (date );
}
/**
* Converts a timestamp to a string.
* @ Param time
* @ Return
*/
Public static string timestamp2str (timestamp time ){
Date = NULL;
If (null! = Time ){
Date = new date (time. gettime ());
}
Return date2str (date, default_format );
}
/** String Conversion Timestamp
* @ Param Str
* @ Return
*/
Public static timestamp str2timestamp (string Str ){
Date = str2date (STR, default_format );
Return new timestamp (date. gettime ());
}
Public static void main (string [] ARGs) throws exception {
String TM = "10:00:00. 123 ";
Timestamp tstamp = str2timestamp (TM );
System. Out. println (tstamp );
System. Out. println (timestamp2str (null ));
}
}