/*
 *
 *  Copyright (C) 2012 Andreas Reichel <andreas@manticore-projects.com>
 *
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or (at
 *  your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
 *
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */

package com.manticore.database;

import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Test {
	public final static Logger logger=Logger.getAnonymousLogger();
	public final static SimpleDateFormat sdf=new SimpleDateFormat("YYYY-MM-DD hh:mm:ss.s");
	public final static String timestampStr="2013-02-11 21:59:02.0";
	
	
	public static java.sql.Timestamp getSqlTimestamp(String s) throws ParseException {
		return new java.sql.Timestamp(sdf.parse(s).getTime());
	}
	
	public static java.sql.Date getSqlDate(String s) throws ParseException {
		return new java.sql.Date(sdf.parse(s).getTime());
	}
	
	public static void main(String[] args) throws ClassNotFoundException, SQLException, ParseException {
		String sqlStr="create table date_test (date_field timestamp)";
		String sqlStr1="insert into date_test values(?)";
		String sqlStr2="select date_field from date_test where date_field=?";
		
		Class.forName("org.postgresql.Driver");
		Connection conn=null;
		PreparedStatement prep=null;
		ResultSet rs=null;
		try {
			conn=DriverManager.getConnection("jdbc:postgresql:test", "test", "password");
			try {
				conn.createStatement().executeUpdate(sqlStr);
			} catch (Exception ex) {
				logger.log(Level.FINER, "Create Table", ex);
			}
					
			prep=conn.prepareStatement(sqlStr1);
			prep.setObject(1, getSqlDate(timestampStr));
			prep.executeUpdate();
			
			prep=conn.prepareStatement(sqlStr2);
			prep.setObject(1, getSqlDate(timestampStr));
			rs=prep.executeQuery();
			
			if (rs.next()) {
				boolean valid = 0==rs.getDate(1).compareTo(sdf.parse(timestampStr));
				logger.info("found date: " + rs.getDate(1) + " which is " + (valid ? " correct" : " NOT correct "));
			}
		
		} finally {
			if (rs!=null) rs.close();
			if (prep!=null) prep.close();
			if (conn!=null) conn.close();
		}
		
	}
}
