How to convert a String to a Calendar object? - java

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";
}

Related

How to fetch Records for a week

I am using Java 7 and fetching records for a week.For valid_from column I am subtracting -7 from current date below. The format of date in DB is 12-FEB-18. For valid_to column I am using sysdate. I am not getting correct valid_from date. Can anyone review this what is wrong here.
Format formatter = new SimpleDateFormat("dd-MMM-yy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
Date todate1 = cal.getTime();
Date startdate = ((DateFormat)formatter).parse(formatter.format(todate1));
System.out.println(todayWithZeroTime);
String sql_qry = "SELECT a.ACCOUNT_ID from tableName a where a.STATUS_TYPE_KEY='ACTIVE' "
+ "and a.VALID_FROM >"
+ startdate+ " and a.VALID_TO > sysdate";
How can I parse only Date here. Currently I am getting Tue Feb 13 00:00:00 GMT 2018. I want 13-FEB-18 which I can send as variable in where condition.
Please suggest
You are converting a Date to a String then back to a Date.
Then you are using this Date object in your query, so it's toString() method gets called and yields a String representation which is probably not the one you wanted.
Avoid the last conversion from String to Date and just use
String startdate = formatter.format(todate1);
Note that you also have to escape the date string with quotes :
String sql_qry = "SELECT a.ACCOUNT_ID from tableName a where "
+ "a.STATUS_TYPE_KEY='ACTIVE' "
+ "and a.VALID_FROM > '"
+ startdate+ "' and a.VALID_TO > sysdate";
Also consider having a look at Java time API and at How to use PreparedStatement

SQL statement in Java to sort by date (month)

I have an SQL table in my Android project, that has a KEY_DATE field in Date format.
KEY_DATE + " DATE,"
My table is populated from the java code (date in dd/mm/yy format).
So now I need to make several date-related queries and something isn't working.
I need to make selections from a table for today, this month and this year.
Here's what I tried:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
Date todayD = new Date();
dateFormat.format(todayD);
String today = dateFormat.format(todayD);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDay = cal.getTime();
dateFormat.format(firstDay);
String selectQuery = "SELECT * FROM " + TABLE_PAYMENTS + "WHERE "
+ KEY_DATE +" BETWEEN " + firstDay + " AND " + today;
The query returns empty even though there's a lot of data for that period.
I believe something is wrong with data formats here. Can you help me to solve this?
Thank you in advance.
You are not formatting firstD, so you only get from the first day of the month at the current time on;
You should either use single quotes around the dates in your queries or use prepared statements, otherwise your server will understand your dates as math operations;
When querying for date ranges, remember that if you don't specify an hour with your date SQL will by default take it as zero hour (0:00:00.0000). If you use "between startDate and today", you get only midnight of today. If you use "between startDate and tomorrow", you get midnight of tomorrow too. You should use "date >= startDate and date < tomorrow" to get the proper range.
When writing queries with dates, I always prefer to use ISO format for the date strings: yyyy-MM-dd.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date todayD = new Date();
cal.setTime(todayD);
cal.add(Calendar.DATE, 1);
Date tomorrowD = cal.getTime();
String today = dateFormat.format(tomorrowD);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstD = cal.getTime();
String firstDay = dateFormat.format(firstD);
String selectQuery = "SELECT * FROM TABLE_PAYMENTS WHERE KEY_DATE >= '" + firstDay + "' AND KEY_DATE < '" + today + "'";
The problem is with the date formats for the data present inside the database and the date formats that you are passing (strings) to the sql query.
It is not a good practice to pass dates as string parameters to the sql query, so I strongly suggest use preparedStatement as shown below:
Date todayD = new Date();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDay = cal.getTime();
String selectQuery = "SELECT * FROM TABLE_PAYMENTS WHERE BETWEEN ? AND ?" ;
//create preparedStatement here
preparedStatement.setDate(1, firstDay);
preparedStatement.setDate(2, todayD);

Java handle dates into database

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());
}
}
}

how to convert string to date and keep the format correct

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.

Retreving date from Hibernate TImestamp

I have a field with temporal type as Timestamp to save both date and time to the database.
#Temporal(TemporalType.TIMESTAMP)
#Column(name="date", nullable=false)
private Date date;
But when displaying the value to the user, I just want to show date part and truncate time part. I tried this but I get ParseException probably because of the Nanosecond part of the Hibernate Timestamp.
SimplDateFormat sd = new SimpleDateFormat("MM/dd/yyyy");
return sd.parse(date.toString());
So how do I retrieve just date from Hibernate Timestamp? Thanks
Just format the date object. The toString method isn't guaranteed to give you a string in a format that can then be parsed.
String dateStr = sd.format(date);
That will give you a date string in MM/dd/yyyy format that you can then convert back into a Date.
Date fancyNancy = sd.parse(dateStr);
* EDIT *
Run this code and verify it prints out the day, month and year with no time.
try {
Date d = new Date();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Original Date: " + d);
System.out.println("Formatted Date: " + df.parse(df.format(d)));
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources