31 July 2017

Java: Convert String Timestamp Calendar Format Date

Convert String Timestamp Calendar
Java 2017
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class demo {

 public static void main(String[] args) throws ParseException {
  
  /* String to Timestamp */
  java.sql.Timestamp timestamp1 = java.sql.Timestamp.valueOf("2007-09-23 10:10:00");
  System.out.println(timestamp1);
  
  /* Date to Timestamp */
  java.util.Date today = new java.util.Date();
  java.sql.Timestamp timestamp2 = new java.sql.Timestamp(today.getTime());
  System.out.println(timestamp2);
  
  /* Calendar */
  Calendar cal = Calendar.getInstance();
  
  /* Format Date */
  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
  
  /* Calendar to String */ 
  if (cal!= null) {
   String str = dateFormat.format(cal.getTime());
   System.out.println(str);
  } 

  /* String to Calendar */
  java.util.Date date = dateFormat.parse("2018-10-23-10-20-00"); //Input String
  cal.setTime(date);
  System.out.println(cal);
  
  /* Calendar to Timestamp */ 
  java.sql.Timestamp timestamp3 = new java.sql.Timestamp(cal.getTimeInMillis());
  System.out.println(timestamp3); //Set to sql
  
  //https://www.mkyong.com/jdbc/how-to-insert-timestamp-value-in-preparedstatement/
 }
}
2007-09-23 10:10:00.0
2017-07-31 21:58:49.118
2017-07-31-21-58
java.util.GregorianCalendar[time=1540264800000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Bangkok",offset=25200000,dstSavings=0,useDaylight=false,transitions=3,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2018,MONTH=9,WEEK_OF_YEAR=43,WEEK_OF_MONTH=4,DAY_OF_MONTH=23,DAY_OF_YEAR=296,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0,HOUR=10,HOUR_OF_DAY=10,MINUTE=20,SECOND=0,MILLISECOND=0,ZONE_OFFSET=25200000,DST_OFFSET=0]
2018-10-23 10:20:00.0

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang