I have a date that I would like to insert into my database in dd/mm/yyyy format(25/12/2014)
My code accepts a Booking object with a date as one of its fields.
My code throws an error at the "Date currentDate = sd.parse(book.GetActualCheckInDate()); statement that says:
no suitable mothod found for parse(java.util.Date)
method java.text.SimpleDateFormat.parse(java.lang.String, java.text.ParsePosition) is not applicable(actual and formal argument lists differ in length)
method java.text.DateFormat.parse(java.lang.String) is not applicable(actual argument java.util.Date cannot be converted to java.lang.String by method invocation conversion)
public int InsertBooking(Booking book) throws SQLException
{
int retCode = 2;
try
{
SimpleDateFormat sd = new SimpleDateFormat("dd/mm/yyyy");
Date currentDate = sd.parse(book.GetActualCheckInDate());
java.sql.Date sqlDate = new java.sql.Date(currentDate.getTime());
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/HotelDatabase");
Statement stmt = conn.createStatement();
String insertStatements = ("INSERT INTO BOOKING " +
"(BOOKINGID, ACTUALCHECKINDATE)" +
"VALUES " + "(" + book.GetBookingID() + "," + "'" + sqlDate + "'" + ")");
}
The first problem that i see is the pattern in the SimpleDateFormat. In dd/mm/yyyy
mm represent minutes. Use instead dd/MM/yyyy.
The second thing, is that are you trying to pass an string to a Date field on the DB. Let JDBC do the job to parse into the correct format for your database using PreparedStatements.
What does book.GetActualCheckInDate() return?
It must be a valid date formatted string. Because parse method is to convert the date in string format to date in Date Formate.
Rather if you want a Date to be converted into a date string in a specified formate then you must use format method of SimpleDateFormat. Check out the below solutions
import java.util.Date;
import java.text.SimpleDateFormat;
public class DateChecker {
public static void main(String[] args) {
try {
String someDate = "22/03/1991";
SimpleDateFormat strToDate = new SimpleDateFormat("dd/MM/yyyy");
Date currentDate = strToDate.parse(someDate);
System.out.println("Date is : " + currentDate);
String dateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
SimpleDateFormat dateToStr = new SimpleDateFormat(dateFormat);
String formattedDate = dateToStr.format(currentDate);
System.out.println("Formated Date is : " + formattedDate);
} catch (Exception ex) {
System.out.println("Exception is : " + ex.getMessage());
}
}
}
Related
I am working on an Android app that frequently travels from Time Zone to TZ. I am getting various errors with times and TZs. The latest error is, when I load the flat file with times (see below), everything looks good. When I save the app environment (aka all variables/objects to sharedprefs), stop and then restart the app the time displayed is no longer local but UTC.
I began developing the app just using the default/local TZ. However, this became very complicated with DST and various TZs. Therefore my current approach is to store time in the app in UTC, and calculate differences between UTC times as needed. Then convert the UTC-stored time to the local TZ on-demand for user interaction.
I recognize there are many posts related to android time. I think I have read most if not all on java.util.date and Joda. However, I am still stuck. So, here goes...
I have 3 sources of time for the app. 1) I read in UTC Strings from a flat file 2) I get milliseconds since the Epoch for system time stamp (in UTC). 3) I get UTC in a string via a rest API. The app does numerous calculations between the 3 categories such as time difference, add time, etc. Below I will post my code for each of these
1 - Convert string UTCs that come from a file
public static Date string2date(String strformat, String strdate){
Date tdate = timestamp();
TimeZone tz = TimeZone.getDefault() ;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
SimpleDateFormat formatter = new SimpleDateFormat(strformat);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateInString = strdate;
try {
tdate = formatter.parse(dateInString);
} catch (ParseException e) {
e.printStackTrace();
}
return tdate;
}
2 - Get milliseconds since Epoch
public static Date timestamp() {
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
//Date currentTime = localCalendar.getTime();
Date currentTime = GetUTCdatetimeAsDate();
return currentTime;
public static Date GetUTCdatetimeAsDate()
{
//note: doesn't check for null
return StringDateToDate(GetUTCdatetimeAsString());
}
public static String GetUTCdatetimeAsString()
{
final SimpleDateFormat sdf = new SimpleDateFormat(longdt);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
return utcTime;
}
public static Date StringDateToDate(String StrDate)
{
Date dateToReturn = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(longdt);
try
{
dateToReturn = (Date)dateFormat.parse(StrDate);
}
catch (ParseException e)
{
e.printStackTrace();
}
return dateToReturn;
}
3 - Get UTC in a string via a rest API (Format is "2017-02-10T01:09:00Z")
try {
Calendar tempCal = ISO8601.toCalendar(dateLocal);
Log.e (" fbu "," fsutc " + tempCal.getTime() );
ISODepDate = tempCal.getTime();
tempCal = ISO8601.toCalendar(dateLocal2);
ISOArrDate = tempCal.getTime();
//ab.setTimeZone(PST);
Log.e (" fbu "," fsutc " + dateLocal + " / " + dateLocal2);
Log.e (" fbu "," fsutc " + ISODepDate + " / " + ISOArrDate);
}
catch (Exception a){
int aa = 1;
Log.e (" exception "," a " + a);
}
public static Calendar toCalendar(final String iso8601string)
throws ParseException {
Calendar calendar = GregorianCalendar.getInstance();
TimeZone tz = TimeZone.getDefault() ;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
String s = iso8601string.replace(".000Z", "+00:00");
try {
s = s.substring(0, 22) + s.substring(23); // to get rid of the ":"
} catch (IndexOutOfBoundsException e) {
throw new ParseException("Invalid length", 0);
}
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
calendar.setTime(date);
return calendar;
}
4 - Finally, here is what I am using to "Display" the above 3 time categories in local time.
public String UTCtoLocal(Date indate, Boolean formatLong) {
Date utcDate = indate;
String result;
//Log.e( " utc "," indate " + indate);
/*utcDate = your own initialization here;*/
Date localDate = new Date(utcDate.getTime() + TimeZone.getDefault().getRawOffset());
//Log.e( " utc "," localdate " + localDate);
if (formatLong){
result = longd.format(localDate);
} else {
result = shortt.format(localDate);
}
return result;
The questions are, given the expectation that I store in UTC and display in Local, a) Have I implemented items 1-4 correctly? b) Will the above code actually store the times in UTC and display in local?
After flat file load everything looks good. After restart the times are displayed in UTC vs Local.
To store a Calendar object in SQLite database, i found that the easiest way is to convert the Calendar object to a string and store it in the database as text.
Now, the problem lies in extracting the stored date from the string.
How do I parse the string containing the Calendar object and set it to a Calendar value?
My code is:
String CREATE_DOCTORS_TABLE = "CREATE TABLE " + TABLE_DOCTORS + "("
+ KEY_ID_DOC + " INTEGER PRIMARY KEY," + KEY_DOCTOR_NAME + " TEXT,"
+ KEY_CLINIC_ADDRESS + " TEXT," + KEY_LAST_CHECKUP + " TEXT" + ");";
db.execSQL(CREATE_DOCTORS_TABLE);
where KEY_LAST_CHECKUP contains a value like this:
java.util.GregorianCalendar[time=?,areFieldsSet=false,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2013,MONTH=4,WEEK_OF_YEAR=29,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=198,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=19,SECOND=47,MILLISECOND=823,ZONE_OFFSET=19800000,DST_OFFSET=0]
and i've stored it in a database this way:
values.put(KEY_LAST_CHECKUP, (doctor.getLastCheckUpDate().toString())); // last check up date
Now, how do i retrieve the DAY, MONTH and YEAR from the stored string?
I read about how to convert a date string to a calendar object here:
How to convert a date String to a Date or Calendar object?
but my string is not just a date string. It contains a lot of other details too.
What is the best way forward?
Change your data model to use a Date. This is the usual type to be stored in the database.
You can set the Date to a Calendar by using
Calendar c = Calendar.getInstance();
c.setTime(date);
To retrieve the Date from a Calendar you can use
date = c.getTime();
Using a String to store a Date in a database needs formatting and parsing of the Strings and also no comparision iside the database can be done.
If you would like to keep string value in KEY_LAST_CHECKUP column. Try to use SimpleDateFormat.
If you keep long value, you don't need to use SimpleDateFormat.
For insert :
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String strDate = simpleFormat.format(doctor.getLastCheckUpDate());
values.put(KEY_LAST_CHECKUP, strDate);
For retrieve:
try {
String strDate = --> from DB
Date parsedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(strDate);
Calendar c = Calendar.getInstance();
c.setTime(parsedDate);
} catch (ParseException e) {
return "Unknown";
}
Hi Iam retrieving the events based on the datetime . When iam passing the datetime as query for getting events from google calender getting below exception.
private static void dateRangeQuery(CalendarService service) throws ServiceException,
IOException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
//get current date time with Calendar()
Date dt = Calendar.getInstance().getTime();
//System.out.println(dateFormat.format(cal.getTime()));
// System.out.println(cal.getTime());
DateTime startTime = DateTime.parseDateTime(dateFormat.format(dt));
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.MINUTE, 20);
System.out.println(dateFormat.format(cal2.getTime()));
System.out.println(cal2.getTime());
DateTime endTime = DateTime.parseDate(dateFormat.format(cal2.getTime()));
CalendarQuery myQuery = new CalendarQuery(eventFeedUrl);
myQuery.setMinimumStartTime(startTime);
myQuery.setMaximumStartTime(endTime);
// Send the request and receive the response:
CalendarEventFeed resultFeed = service.query(myQuery,
CalendarEventFeed.class);
//System.out.println("Events from " + startTime.toString() + " to "
// + endTime.toString() + ":");
System.out.println();
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEventEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
System.out.println();
}
Exception below:
Exception in thread "main" java.lang.NumberFormatException: Invalid date/time format.
at com.google.gdata.data.DateTime.parseDateTime(DateTime.java:303)
at GoogleCalender.dateRangeQuery(GoogleCalender.java:185)
at GoogleCalender.main(GoogleCalender.java:115)
please can anyone suggest how to resolve this issue
The XML dateTime pattern, expected by DateTime.parseDateTime(), is [-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm].
So, the date should be formatted using the SimpleDateFormat yyyy-MM-dd'T'HH:mm:ss pattern (not tested).
But an even simpler way would be to simply use the DateTime constructor which takes a java.util.Date as argument, instead of transforming the Date to a String, and then thuis Date to a DateTime.
My database column datatype is timestamp. How do I insert the current date and time using a PreparedStatement or Statement?
I have tried this:
java.util.Date date = new java.util.Date();
System.out.println("Current Date : " + dateFormat.format(date));
pstmt.setDate(9, new java.sql.Timestamp(date.getTime()));
But the value inserted in the table is 1328847536746. This not right, i am using sqlite
There is a separate Timestamp value class in java.sql.
pstmt.setTimeStamp(9, new java.sql.Timestamp(date.getTime()));
The javadoc explains:
public class Timestamp
extends Date
A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value.
Use setTimestamp().
pstmt.setTimestamp(9, Timestamp.valueOf("2002-03-13 11:10:15.01"));
This is the code I've used so far to get it done
Timestamp nextRunTimestamp = null;
if(endDate != null || !endDate.equalsIgnoreCase(""))
{
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
dateFormat.parse(endDate);
Calendar tempDate = dateFormat.getCalendar();
tempDate.set(Calendar.HOUR, nextRunTime.get(Calendar.HOUR));
tempDate.set(Calendar.MINUTE, nextRunTime.get(Calendar.MINUTE));
tempDate.set(Calendar.SECOND, nextRunTime.get(Calendar.SECOND));
tempDate.set(Calendar.MILLISECOND, nextRunTime.get(Calendar.MILLISECOND));
if(nextRunTime.before(tempDate) || nextRunTime.equals(tempDate))
{
nextRunTimestamp = new Timestamp(nextRunTime.getTimeInMillis());
}
}
else
{
nextRunTimestamp = new Timestamp(nextRunTime.getTimeInMillis());
}
statement.setTimestamp(2, nextRunTimestamp);
statement.setInt(3, result.getInt("id"));
statement.executeUpdate();
DateFormat df = new SimpleDateFormat(yyyy/MM/dd HH:mm:ss); // any Date format
System.out.println("Current Date : " + df.format(new Date()));
pstmt.setDate(9, to_timestamp(df.format(new Date()),'YYYY/MM/DD HH24:MI:SS'));
Here you can use TO_DATE('todayDate', 'YYYY/MM/DD HH24:MI:SS') or
TO_TIMESTAMP('todayDate', 'YYYY/MM/DD HH24:MI:SS')
I am reading in a String from a text file which contains a date in the form of yyMMdd I then want to convert it to type date but when I do that it loses its format. here is an exmaple of what I have tried
String strDate = matcher.group(10); // strDate would contain 111107
SimpleDateFormat formatter1 = new SimpleDateFormat("yyMMdd");
Date date = formatter1.parse(strDate); // after parsing it, the format changes to Thu Nov 03 00:00:00 EDT 2011
But if I take date and put it back into a string like so String tDate = formatter1.format(date); the string then contains the date in the format Id like to see 111107.
Is there a way I can do this? maybe if I could some how call the format function to return a date object instead of String, thanks.
Edit
I read a list of dates in from a file and load them into a map I then compare those dates to the current date which is also in the yyMMdd format and then if the date from the map is more then a week earlier than the current date I prompt the user for input and then write the date and other related info to a file, in the yyMMdd format. The reason I use a map is each line of the text file contains some information and a unique name, and I compared the date for that specific line of data so I do a map.get(aName)
here is the code, hope it helps
dbConnect();
stmt = conn.createStatement();
String query = "select * from OBJECT_BAC_EV where instance = 12";//VALUE <> 'Normal'";
rslt = stmt.executeQuery(query);
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
String dateNow = formatter.format(currentDate.getTime());
Date curDate = (Date)formatter.parse(dateNow);
currentDate.setTime(curDate);
currentDate.add(Calendar.DAY_OF_MONTH, -7);
dateNow = formatter.format(currentDate.getTime());
curDate = (Date)formatter.parse(dateNow);
Calendar cDate = Calendar.getInstance();
SimpleDateFormat f = new SimpleDateFormat("yyMMdd");
String strDate = f.format(cDate.getTime());
while(rslt.next())
{
System.out.println(rslt.getRow());
String aValue = rslt.getString("VALUE");
String aName = rslt.getString("NAME");
String aObjRef = rslt.getString("ObjRef");
if(aNoteMap.containsKey(aName))
{
String n = aNoteMap.get(aName);
if(aDateMap.get(aName).before(curDate))
{
int answer = JOptionPane.showConfirmDialog(null, "Would you like to use last weeks note? " + n, "Hey", JOptionPane.YES_NO_OPTION);
if( answer == JOptionPane.YES_OPTION)
{
output.write(aName + " " + aObjRef + " " + aValue + " " + aDateMap.get(aName) + " "
+ n + (System.getProperty("line.separator")));
}
else if( answer == JOptionPane.NO_OPTION)
{
String newNote = JOptionPane.showInputDialog("Enter new note");
output.write(aName + " " + aObjRef + " " + aValue + " " + aDateMap.get(aName) + " "
+ newNote + (System.getProperty("line.separator")));
}
}
else
output.write(aName + " " + aObjRef + " " + aValue + " " + aDateMap.get(aName) + " "
+ n + (System.getProperty("line.separator")));
}
else
output.write(aName + " " + aObjRef + " " + aValue + " " + strDate + " "
+ "" + (System.getProperty("line.separator")));
}
System.out.println("its closing output..");
output.close();
}
The Date class has no "internal" format, it only represents date elements. To output it using a specific format, you need to do the way you did: String tDate = formatter1.format(date);
The reason why you think it has the "wrong format" is probably because when you try to output it, it does a toString() by default, which doesn't format it the way you want.
If you give us more details about how you want to use that date (include your code), then we might be able to provide suggestions on how to inject the formatter into it.
Date always stores the complete information including time. If you parse the date with a SimpleDateFormat that does not contain time info, these fields are set to 0 as in your example.
Date does not store any format info itself.
The SimpleDateFormat.format method always returns a String. It represents the 'date' parameter as a String, with the specified format. For example:
SimpleDateFormat sdf = new SimpleDateFormat('yyMMdd');
Date date = sdf.parse("110510");
String sDate = sdf.format(date); //"110510"
SimpleDateFormat sdf2 = new SimpleDateFormat('yyyy.MM.dd');
String sDate2 = sdf2.format(date); //2011.05.10
It's the best thing for formatting a Date Object.
Written using joda-time, it would like this :
String str = "110107";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendYearOfCentury(2, 2)
.appendMonthOfYear(2)
.appendDayOfWeek(2)
.toFormatter();
DateTime dateFromDB = formatter.parseDateTime(str);//create DateTime instance
System.out.println("Date:" + formatter.print(dateFromDB));//toString in required format
And it has many other benefits, apparently it will replace the existing Java date libs, which have always been rather painful, in upcoming java releases.
One of the benefits is
DateTime now = new DateTime();
Integer compared = now.minusWeeks(1).compareTo(dateFromDB);
And compareTo does the expected
You could try something like:
class MyDate extends java.util.Date {
static final SimpleDateFormat yymmddFormat = new SimpleDateFormat("yyMMdd");
public MyDate (String s) throws ParseException {
super(yymmddFormat.parse(s).getTime());
}
public String toString () {
return yymmddFormat.format(this);
}
}
Use this class everywhere you currently use a Date object. This should make all your dates look as you want them.