Set java.util.Date to beginning of the day - java

I want to reset java.util.Date to the beginning of the day
using
Date date = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();
with
Date date = new Date();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String s=df.format(date);
try {
date = df.parse(s);
} catch (ParseException ex) {
}
Which one is better?

This one's better in terms of clarity and readability, though both gives same output.
Date date = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();

With help of Apache Commons org.apache.commons.lang3.time.DateUtils you can also get the desired result like this:
DateUtils.truncate(new java.util.Date(), java.util.Calendar.DATE));

First solution (manipulation via Calendar) is definitly better. The second solution is just a rather ugly workaround using string-manipulation, that will most likely be slower than the first one.

You can for first approach and you need not set time in Calendar.
// Date date = new Date();
Calendar cal = new GregorianCalendar();
// cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date date = cal.getTime();

Related

Error when trying to cast from Calendar to Date then to sql.Date [duplicate]

Calendar cal;
String sql = "INSERT INTO ttable (dt) values (?);"
//dt is a dateTime field in ttable
PreparedStatement stmt = connection.prepareStatement(sql);
stmt = setDate(1,cal); //not working
stmt.execute();
stmt.close();
I would like to convert cal to a Date type to insert into table.
There is a getTime() method (unsure why it's not called getDate).
Edit: Just realized you need a java.sql.Date. One of the answers which use cal.getTimeInMillis() is what you need.
Did you try cal.getTime()? This gets the date representation.
You might also want to look at the javadoc.
Use stmt.setDate(1, new java.sql.Date(cal.getTimeInMillis()))
Converting is easy, setting date and time is a little tricky. Here's an example:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
stmt.setDate(1, new java.sql.Date(cal.getTimeInMillis()));
Here is a simple way to convert Calendar values into Date instances.
Calendar C = new GregorianCalendar(1993,9,21);
Date DD = C.getTime();
System.out.println(DD);
stmt.setDate(1, new java.sql.Date(cal.getTime().getTime()));
Calendar cal = Calendar.getInstance(); //This to obtain today's date in our Calendar var.
java.sql.Date date = new Date (cal.getTimeInMillis());
I found this code works:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Calendar calendar = new GregorianCalendar(2013,0,31);
System.out.println(sdf.format(calendar.getTime()));
you can find the rest in this tutorial:
http://www.mkyong.com/java/java-date-and-calendar-examples/

Java : How to parse date format to show specific output format?

In my app, i retrieve date from my database in a specific format. (Generated by PHP)
I would like to show a specific output in my Android app for this cases :
Input format from database : 2014-05-30 17:50:50
I would like to be able to show this format in a TexView :
if the date refers to today, i would like to show this format :
Today - 17h50
if the date refers to yesterday, i would to show this format :
Yesterday - 17h50
And for others days :
5 June - 17h50
How can i do that ?
[UPDATE]
String dateDebut = annonce.getDate_debut();
SimpleDateFormat inDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // inputFormat
SimpleDateFormat TodayDF = new SimpleDateFormat("HH'h'mm"); //OutputFormat For today and yesterday
SimpleDateFormat FullDF = new SimpleDateFormat("dd MMM - HH'h'mm"); //Outputformat long
Date inDate = null;
try {
inDate = inDF.parse(dateDebut);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//calendar for inputday
Calendar inCal = new GregorianCalendar();
inCal.setTime(inDate);
//startOfToday
Calendar cStartOfDate = new GregorianCalendar();
cStartOfDate.set(Calendar.HOUR, 0);
cStartOfDate.set(Calendar.MINUTE, 0);
cStartOfDate.set(Calendar.SECOND, 0);
cStartOfDate.set(Calendar.MILLISECOND, 0);
//endOfToday
Calendar cEndOfDate = new GregorianCalendar();
cEndOfDate.set(Calendar.HOUR, 23);
cEndOfDate.set(Calendar.MINUTE, 59);
cEndOfDate.set(Calendar.SECOND, 59);
//startOfYesterday
Calendar cStartOfYesterday = new GregorianCalendar();
cStartOfYesterday.set(Calendar.HOUR, 0);
cStartOfYesterday.set(Calendar.MINUTE, 0);
cStartOfYesterday.set(Calendar.SECOND, 0);
cStartOfYesterday.set(Calendar.MILLISECOND, 0);
//endOfYesterday
Calendar cEndOfYesterday = new GregorianCalendar();
cEndOfYesterday.set(Calendar.HOUR, 23);
cEndOfYesterday.set(Calendar.MINUTE, 59);
cEndOfYesterday.set(Calendar.SECOND, 59);
if (cStartOfDate.before(inCal) && cEndOfDate.after(inCal)){
System.out.println("Aujourd'hui - "+TodayDF.format(inDate));
viewHolder.dateDebut.setText("Aujourd'hui - "+TodayDF.format(inDate));
} else if (cStartOfYesterday.before(inCal) && cEndOfYesterday.after(inCal)){
System.out.println("Hier - "+TodayDF.format(inDate));
viewHolder.dateDebut.setText("Hier - "+TodayDF.format(inDate));
} else {
System.out.println(FullDF.format(inDate));
viewHolder.dateDebut.setText(FullDF.format(inDate));
}
Try out this Code:
DateFormat inDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // inputFormat
DateFormat TodayDF = new SimpleDateFormat("HH'h'mm"); //OutputFormat For today and yesterday
DateFormat FullDF = new SimpleDateFormat("dd MMM - HH'h'mm"); //Outputformat long
Date inDate = inDF.parse("2014-06-05 17:50:50");
//calendar for inputday
Calendar inCal = new GregorianCalendar();
inCal.setTime(inDate);
//startOfToday
Calendar cStartOfDate = new GregorianCalendar();
cStartOfDate.set(Calendar.HOUR_OF_DAY, 0);
cStartOfDate.set(Calendar.MINUTE, 0);
cStartOfDate.set(Calendar.SECOND, 0);
cStartOfDate.set(Calendar.MILLISECOND, 0);
//endOfToday
Calendar cEndOfDate = new GregorianCalendar();
cEndOfDate.set(Calendar.HOUR_OF_DAY, 23);
cEndOfDate.set(Calendar.MINUTE, 59);
cEndOfDate.set(Calendar.SECOND, 59);
//startOfYesterday
Calendar cStartOfYesterday = new GregorianCalendar();
cStartOfYesterday.set(Calendar.HOUR_OF_DAY, 0);
cStartOfYesterday.set(Calendar.MINUTE, 0);
cStartOfYesterday.set(Calendar.SECOND, 0);
cStartOfYesterday.set(Calendar.MILLISECOND, 0);
//endOfYesterday
Calendar cEndOfYesterday = new GregorianCalendar();
cEndOfYesterday.set(Calendar.HOUR_OF_DAY, 23);
cEndOfYesterday.set(Calendar.MINUTE, 59);
cEndOfYesterday.set(Calendar.SECOND, 59);
if (cStartOfDate.before(inCal) && cEndOfDate.after(inCal)){
System.out.println("Today "+TodayDF.format(inDate));
} else if (cStartOfYesterday.before(inCal) && cEndOfYesterday.after(inCal)){
System.out.println("Yesterday"+TodayDF.format(inDate));
} else {
System.out.println(FullDF.format(inDate));
}
First convert the date obtained from database to a Calendar instance
Today and Yesterday can be identified with the Calendar instance
For the other formats use below:
Code:
Calendar cal = Calendar.getInstance();
new SimpleDateFormat("dd MMMM - HH").format(cal.getTime())+
"h" + new SimpleDateFormat("mm").format(cal.getTime())
Here is a complete solution. I did not try it, but it should work.
NB: Be carefull about input limits: I am not sure it will work if the date is 01/01/2015 for example. I let you test this.
private boolean checkSameDate(Calendar cal1, Calendar cal2) {
if ((cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR))
&& (cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR))) {
return true;
}
return false;
}
private void checkDate(Date date) {
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
Calendar cal2 = new GregorianCalendar();
cal2.setTime(date);
cal.add(Calendar.DAY_OF_YEAR, 1);
if (checkSameDate(cal, cal2)) {
// Your input date is tomorrow.
} else {
cal.add(Calendar.DAY_OF_YEAR, -2);
if (checkSameDate(cal, cal2)) {
// Your input date is yesterday.
} else {
DateFormat sdf = new SimpleDateFormat("dd MMMM - HH:mm");
System.out.println(sdf.format(date));
}
}
}
Edit
Sorry, I think it will not work for a date in 31/12/YYYY-1 when today is 01/01/YYYY. Maybe you can fix this code with this kind of solution: Check if one date is exactly 24 hours or more after another
For SimpleDateFormat, I let you check here https://ideone.com/dsxKN9 if this is the format you need.
Edit 2
I just see that you want today and not tomorrow :). My bad! I'll try fix this, but if you understand the logical, you'll be able to do it.
You can do it in using this function:
public static String convertDate(String stringDate, String oldFormat) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(oldFormat);
Date date = sdf.parse(stringDate);
double daysAgo = (System.currentTimeMillis() - date.getTime()) / (24 * 60 * 60 * 1000d);
System.out.println(daysAgo);
String newFormat;
if (daysAgo<=0){
newFormat="'Today -' HH'h'mm";
}
else if (daysAgo>=0 && daysAgo<=1){
newFormat="'Yesterday -' HH'h'mm";
}
else {
newFormat="d MMMM '-' HH'h'mm";
}
sdf.applyPattern(newFormat);
return sdf.format(date);
}
And the usage would be:
String newDate = convertDate("2014-06-03 17:50:50", "yyyy-MM-dd HH:mm:ss");

How to get current date with custom hour?

I need to get actual date with custom hour so I create this code:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
Calendar output = Calendar.getInstance();
output.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 1, 0);
output.getTime();
I hope it works but it seems a litle bit complicated.
Is there some other way how to get date with custom hour?
Is there some other way how to get date with custom hour ?
Personally I'd use Joda Time instead:
// Ideally use an injectable clock...
LocalDate today = new LocalDate();
// If this is effectively constant, extract it to a final static field
LocalTime time = new LocalTime(1, 0);
// Or use toDateTime(...) depending on what you're trying to accomplish
LocalDateTime todayAtTime = today.toLocalDateTime(time);
Joda Time has a much more pleasant API than java.util.{Date, Calendar}
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 0);
cal.getTime()
what about this :
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, your_custom_hour);
your_custom_hour : 0-23
Other than use Joda time I'd do it slightly cleaner:
int hour = 1;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, hour);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar.getInstance() returns the current date and time anyway so setTime(new Date()) is unnecessary.

startime to be set in calendar

I want jan 1st 2012 as long value from calendar object as a start time how to get this,i am doing as below
Calendar today = Calendar.getInstance();
today.set(Calendar.MILLISECOND, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.HOUR, 0);
long startTime = today.getTime().getTime();
Try this:
Calendar firstOfYear = Calendar.getInstance();
firstOfYear.clear();
firstOfYear.set(Calendar.YEAR, 2012);
firstOfYear.set(Calendar.DAY_OF_YEAR,1); //first day of the year.
this is the another way
String str_date="01-JAN-2012";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MMM-yyyy");
date = (Date)formatter.parse(str_date);
Calendar cal=Calendar.getInstance();
cal.setTime(date);
System.out.println("=======>"+cal.getTimeInMillis());

How to compare dates in hibernate

In my Data base dates are as 2012-04-09 04:02:53 2012-04-09 04:04:51 2012-04-08 04:04:51, etc, I need to retrieve data which have current date in there date field. I mean i need to match only 2012-04-09' . How can i do it using hibernate criteria.
Use Restrictions.between() to generate a where clause which the date column is between '2012-04-09 00:00:00' and '2012-04-09 23:59:59'
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fromDate = df.parse("2012-04-09 00:00:00");
Date toDate = df.parse("2012-04-09 23:59:59");
criteria.add(Restrictions.between("dateField", fromDate, toDate));
Please note that all the properties used in the Criteria API is the Java property name , but not the actual column name.
Update: Get fromDate and toDate for the current date using JDK only
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date fromDate = calendar.getTime();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Date toDate = calendar.getTime();
criteria.add(Restrictions.between("dateField", fromDate, toDate));
Like this?
criteria.add(Expression.eq("yourDate", aDate))
fromDate.setTime(new Date());
fromDate.set(Calendar.HOUR_OF_DAY, 0);
fromDate.set(Calendar.MINUTE, 0);
fromDate.set(Calendar.SECOND, 0);
fromDate.set(Calendar.MILLISECOND, 0);
This code is extremely dangerous ... if the day is switch to daylight saving time (e.g. 06.04.1980) you end up in following exception!!!
java.lang.IllegalArgumentException: HOUR_OF_DAY: 0 -> 1day
HQL: from human pat where year(pat.birthdate) = :start_day and month(pat.birthdate) = :start_month and year(pat.birthdate) = :start_year ");
params.put("start_day", startDate.get(Calendar.DAY_OF_MONTH));
params.put("start_month", startDate.get(Calendar.MONTH) + 1);
params.put("start_year", startDate.get(Calendar.YEAR));
The year/month/day functions use the underlying db functions (extract, ...) and compares only these values. Therefore I did not need to set the time to 0 which leads to the above described exception.
just an example out of my mind how I solved the problem! Maybe it helps
How-to do it in Hibernate has already been said. You can prepare the Timestamp objects in the Java code using, for example, the following aproach:
Calendar cFrom = Calendar.getInstance();
cFrom.setTime(new Date()); /* today */
cFrom.set(Calendar.HOUR_OF_DAY, 0);
cFrom.set(Calendar.MINUTE, 0);
cFrom.set(Calendar.SECOND, 0);
cFrom.set(Calendar.MILLISECOND, 0);
Timestamp from = new Timestamp(cFrom.getTime().getTime());
Calendar cTo = Calendar.getInstance();
cTo.setTime(new Date()); /* today */
cTo.set(Calendar.HOUR_OF_DAY, 23);
cTo.set(Calendar.MINUTE, 59);
cTo.set(Calendar.SECOND, 59);
cTo.set(Calendar.MILLISECOND, 999);
Timestamp to = new Timestamp(cTo.getTime().getTime());
final String QUERY = ""
+ "SELECT tr "
+ "FROM Type tr "
+ "WHERE tr.timestamp >= :timestampFrom AND tr.timestamp <= :timestampTo";
Query query = entityManager.createQuery(QUERY);
query.setParameter("timestampFrom", from);
query.setParameter("timestampTo", to);
#SuppressWarnings("unchecked")
List<Type> ts = (List<Type>)query.getResultList();
The easiest way is to fetch all records having date between the beginning and end of a given day:
WHERE date BETWEEN :from AND :to
And compute from and to in your Java code.
For computing midnights:
import static org.apache.commons.lang.time.DateUtils.ceiling;
import static org.apache.commons.lang.time.DateUtils.truncate;
Date someDay = new Date();
Date from = truncate(someDay, Calendar.DAY_OF_MONTH);
Date to = new Date(ceiling(someDay, Calendar.DAY_OF_MONTH).getTime() - 1);
Restrictions.between("dateColumn", midnight1, midnight2)
The following code will work
Calendar fromDate = Calendar.getInstance();
fromDate.setTime(new Date());
fromDate.set(Calendar.HOUR_OF_DAY, 0);
fromDate.set(Calendar.MINUTE, 0);
fromDate.set(Calendar.SECOND, 0);
fromDate.set(Calendar.MILLISECOND, 0);
Calendar toDate = Calendar.getInstance();
toDate.setTime(new Date());
toDate.set(Calendar.HOUR_OF_DAY, 23);
toDate.set(Calendar.MINUTE, 59);
toDate.set(Calendar.SECOND, 59);
toDate.set(Calendar.MILLISECOND, 999);
criteria.add(Restrictions.between("loadDate", fromDate.getTime(),
toDate.getTime()));
// datetime comparison Hibernate 4.3
Select c from Customer c where c.date<{d '2000-01-01'}

Categories

Resources