This question already has answers here:
How to add one day to a date? [duplicate]
(18 answers)
Closed 9 years ago.
I need the get the current date like "yyyy-mm-dd" so not the hours and minutes.
And I need the current day 24hours futher so 1 day futher.
I need it in my fql query this is my query:
String FQL + = .... AND start_time<'" + startTime + "' AND start_time>'" + endTime + "' LIMIT 25"
I'm doing this with this code but it doesn't work:
Date myDate = new Date();
Date endTime = new Date(myDate.getTime() + 86400000L);
Date startTime = new Date(myDate.getTime());
When startTime < endTime
because
Date startTime = new Date(myDate.getTime());
Date endTime = new Date(myDate.getTime() + 86400000L);
how can the expression
X<'" + startTime + "' AND X>'" + endTime + "'
ever by true?
X < startTime X > endTime
---------------------------+---------------------+--------------------------
startTime endTime
I replaced it with X to better distinguish between start_time and startTime
Use java.util.Calendar
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 1); // adds 1 day
calendar.getTime(); // returns the Date
Good Luck!
Use a Calendar instance.
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("yyy-MM-dd");
String startTime = sf.format(calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, 1);
String endTime = sf.format(calendar.getTime());
As Rene rightly points out, start_time needs to be GREATER than startTime (start_time > startTime) and SMALLER than your endTime (start_time < endTime).
Let me also point you to joda-time, which makes handling of dates much more comfortable. But for your purpose, the code above is just fine.
edit:
I read it as if the question was only about the format, but what René Link pointed out is right: Your query can never yield any results.
With java.util.Date it's something like:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
long now = System.currentTimeMillis();
Date today = new Date(now);
Date tomorrow = new Date(now + 86400000); // 24 * 60 * 60 * 1000
System.out.println("Today: " + dateFormat.format(today) +
"\nTomorrow: " + dateFormat.format(tomorrow));
With java.sql.Date it becomes slightly simpler:
long now = System.currentTimeMillis();
Date today = new Date(now);
Date tomorrow = new Date(now + 86400000);
System.out.println("Today: " + today + "\nTomorrow: " + tomorrow);
And maybe you might want to use java.util.Calendar.getInstance().getTime() instead of the System.currentTimeMillis() to create the first date. You then simply have to get the first date's time in millis to add the 86400000 to the second date.
Related
This question already has answers here:
How can I convert a Unix timestamp to DateTime and vice versa?
(21 answers)
Closed 6 years ago.
I need to calculate a expiry date difference.
I will get this epoch time:
1481410800 (06-Dec-2016 (14:42))
now I want to calculate the days until the expiry date (1481410800)
Calendar now = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy (HH:mm)", Locale.getDefault());
//Expiry Date
long unixSecondsExpiry = 1481410800; //unixSeconds
Date expiryDate = new Date(unixSecondsExpiry*1000L);
long currentDate = now.get(Calendar.SECOND);
long diff = unixSecondsExpiry - currentDate;
long days = diff / (24l * 60l * 60l * 1000l);
String formattedExpiryDate = sdf.format(expiryDate);
String formattedDateNow = sdf.format(new Date());
Log.w("RUNTEST", "formattedDateNow: " + formattedDateNow);
Log.w("RUNTEST", "formattedExpiryDate: " + formattedExpiryDate);
Log.w("RUNTEST", "days: " + days);
I keep getting 17 days but it should be 5 days till expiry.
RUNTEST: formattedDateNow: 06-Dec-2016 (14:42)
RUNTEST: formattedExpiryDate: 11-Dec-2016 (07:00)
RUNTEST: days: 17
Here you are using new Date()
String formattedDateNow = sdf.format(new Date());
but the calculation is using
long currentDate = now.get(Calendar.SECOND);
Why not just use
long currentDate = new Date().getTime ();
edit
getting the SECONDS from a calendar is just getting the current seconds counter
Field number for get and set indicating the second within the minute.
E.g., at 10:04:15.250 PM the SECOND is 15.
I am having java.sql.date and java.sql.time objects, I need to find the time duration between the dates.
So i am creating java.sql.timestamp object by using above date and time object
Timestamp timestamp1 = new Timestamp(StartDate.getYear(),
StartDate.getMonth(), StartDate.getDay(),
StartTime.getHours(), StartTime.getMinutes(), 00,
00);
Here is mycode
String date = "2010-01-05";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date3 = null;
try {
date3 = sdf1.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
Date StartDate = new Date(date3.getTime());
System.out.println("Date " + StartDate);
String date2 = "2010-01-06";
java.util.Date date4 = null;
try {
date4 = sdf1.parse(date2);
} catch (ParseException exception) {
exception.printStackTrace();
}
Date EndDate = new Date(date4.getTime());
System.out.println("Date " + EndDate);
String time = "01:00";
DateFormat formatter = new SimpleDateFormat("HH:mm");
java.sql.Time StartTime = null;
try {
StartTime = new java.sql.Time(formatter.parse(time).getTime());
} catch (ParseException exception2) {
exception2.printStackTrace();
}
System.out.println("TIMEEEEEEEEEE====" + StartTime);
String time2 = "02:00";
java.sql.Time EndTime = null;
try {
EndTime = new java.sql.Time(formatter.parse(time2).getTime());
} catch (ParseException exception3) {
exception3.printStackTrace();
}
System.out.println("TIMEEEEEEEEEE====" + EndTime);
Timestamp timestamp1 = new Timestamp(StartDate.getYear(),
StartDate.getMonth(), StartDate.getDay(),
StartTime.getHours(), StartTime.getMinutes(), 00,
00);
Timestamp timestamp2 = new Timestamp(EndDate.getYear(),
EndDate.getMonth(), EndDate.getDay(),
EndTime.getHours(), EndTime.getMinutes(), 00, 00);
long milliseconds = timestamp2.getTime() - timestamp1.getTime();
int seconds = (int) milliseconds / 1000;
// calculate hours minutes and seconds
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
seconds = (seconds % 3600) % 60;
System.out.println(hours+"h:"+minutes+"m:"+"00s");
Test case
when I give date as 2010-01-05 and date2 as 2010-01-06 I am getting output as below
Date 2010-01-05
Date 2010-01-06
TIMEEEEEEEEEE====01:00:00
TIMEEEEEEEEEE====02:00:00
25h:0m:00s
when I give date as 2010-01-05 and date2 as 2010-01-11 I am getting output in negative value as below
Date 2010-01-05
Date 2010-01-11
TIMEEEEEEEEEE====01:00:00
TIMEEEEEEEEEE====02:00:00
-23h:0m:00s
Help me to correct if I am doing something wrong.
Thanks in advance.
Manual time calculation:-
Converts Date in milliseconds (ms) and calculate the differences between two dates, with following rules :
1000 milliseconds = 1 second
60 seconds = 1 minute
60 minutes = 1 hour
24 hours = 1 day
Sample Example:-
package com.dps2.practice.dyuti;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDifferentExample {
public static void main(String[] args) {
String dateStart = "08/11/2016 09:29:58";
String dateStop = "08/12/2016 10:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem with your calculation is this: StartDate.getDay() etc.
getDay() will return the number of day of the week (read the JavaDoc) and not the day of the month. You'll need to use getDate() instead.
To illustrate the problem using your values: 2010-01-05 will return 2 for getDay() and thus you are getting 2010-01-02 as your timestamp. 2010-01-11 will return 1 for getDay() (it's 6 days later, i.e. (2 + 6) % 7 = 1) and hence your second timestamp becomes 2010-01-01. Now the second timestamp is before the first and hence you get a negative value.
However, as I already stated in my comments you should try and use some library or at least the non-deprecated built-in functionality for those calculations to save you a lot of headaches (I suggest you watch this video to get an idea of the challenges: https://youtube.com/watch?v=-5wpm-gesOY ).
The java.sql date-time classes are meant only for exchanging data with databases. Do not use them for business logic. Also, they are part of the troublesome, poorly designed, and confusing old legacy date-time classes. Avoid them all.
java.time
The java.time classes built into Java 8 and later supplant the old classes you are using. Much simpler now.
LocalDate ld = LocalDate.parse ( "2010-01-06" );
LocalTime lt = LocalTime.parse ( "01:00" );
LocalDateTime earlier = LocalDateTime.of ( ld , lt );
LocalDateTime later = earlier.plusHours ( 7 );
The Duration class represents a span of time as a total number of seconds and nanoseconds. Its toString method generates a String in the standard ISO 8601 format PnYnMnDTnHnMnS. This format uses P to mark the beginning, and the T to separate year-months-days from hours-minutes-seconds portion. The Duration and Period classes can both parse and generate such Strings.
Duration duration = Duration.between ( earlier , later );
In Java 8, Duration class inexplicably lacks getter methods for each part: days, hours, minutes, seconds, fraction-of-second. Java 9 rectifies this omission with new getPart methods.
Dump to console.
System.out.println ( "earlier: " + earlier + " | later: " + later + " | duration: " + duration );
earlier: 2010-01-06T01:00 | later: 2010-01-06T08:00 | duration: PT7H
Time zone
Be aware that your inputs lacked any information about offset-from-UTC or time zone. So the math seen above is performed assuming generic 24-hour days. Real-world anomalies such as Daylight Saving Time (DST) are ignored.
If you did indeed intend time zones, assign them via the atZone method to instantiate OffsetDateTime or ZonedDateTime objects.
That's a complicated code you have in your question there. You can make it quite easy by using java.util.concurrent.TimeUnit class.
Output
Date Tue Jan 05 00:00:00 UTC 2010
Date Wed Jan 06 00:00:00 UTC 2010
difference is:
24 hours : 1440 minutes : 86400 seconds
Code
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
public class HelloWorld {
public static void main(String[] args) {
String date = "2010-01-05";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date3 = null;
try {
date3 = sdf1.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
Date StartDate = new Date(date3.getTime());
System.out.println("Date " + StartDate);
String date2 = "2010-01-06";
java.util.Date date4 = null;
try {
date4 = sdf1.parse(date2);
} catch (Exception exception) {
exception.printStackTrace();
}
Date EndDate = new Date(date4.getTime());
System.out.println("Date " + EndDate);
long dateStart = StartDate.getTime(), dateStop = EndDate.getTime();
long diff = dateStop - dateStart;
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(diff);
long diffInHours = TimeUnit.MILLISECONDS.toHours(diff);
System.out.println("\n\ndifference is:\n");
System.out.println(diffInHours + " hours : " + diffInMinutes + " minutes : " + diffInSeconds + " seconds");
}
}
Below is my code which checks the date which is stored in database with the current system date and calculates the days and if that days is lesser than the 180 days it will print something else print nothing,this code works great in an normal java program(with out using swings concept) if it is used with the swing program i changed the sql query to check get the date from the database based on the department and staff names which is entered in the text fields,i coded this code inside an jbutton,in the output it just prints the current system date but not calculates the days between the selected date and the current system dates,friends this is the problem am facing kindly need your help friends....thanks in advance..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/leave", "root", "");
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery("select * from staff where depmt='" + txt1 + "' AND staffs='" + txt2 + "'");
Calendar javaCalendar = null;
String currentDate = "";
javaCalendar = Calendar.getInstance();
currentDate = javaCalendar.get(Calendar.DATE) + "/" + (javaCalendar.get(Calendar.MONTH) + 1) + "/" + javaCalendar.get(Calendar.YEAR);
int cdate = javaCalendar.get(Calendar.DATE);
int cmonth = (javaCalendar.get(Calendar.MONTH) + 1);
int cyear = javaCalendar.get(Calendar.YEAR);
int z = 0;
int date = 0, month = 0, year = 0;
System.out.println("Current Date\t" + currentDate);
System.out.println("\n");
while (rs.next()) {
date = rs.getInt(3);
month = rs.getInt(4);
year = rs.getInt(5);
System.out.println("Random Date\t" + date + "/" + month + "/" + year + "\n");
int d = (date - cdate);
int m = month - cmonth;
int y = year - cyear;
int d1 = java.lang.Math.abs(d);
int d2 = java.lang.Math.abs(m);
int d3 = java.lang.Math.abs(y);
z = d1 + (d2 * 30) + (d3 * 365);
if (z >= 180) {
System.out.println("something");
0
} else {
System.out.println("nothing");
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
//e.printStackTrace();
}
// TODO add your handling code here:
}
You should really use prepared statements cause this way your query is prone to sql injections.
Date formatter insted of concating string for currentdate
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(todaysDate);
Also it seems like your not closeing the connection that may be another issue.
Is there any reason for storeing the date in 3 separate columns?
Your algorithm to calculate the day difference between two dates is broken. It does not take in account different month lengths or leap years.
Unfortunately Java Calendar does not offer this feature at all. So either you apply your own homegrown algorithm (not easy, but in web there are some sources how to map a gregorian date to epoch days) or you use JodaTime like this way:
LocalDate db = new LocalDate(year, month, date);
int days = Days.daysBetween(db, LocalDate.now()).getDays();
Note that the result will be negative if db date is in the future. After all you can greatly shorten your code and abandon all Calendar stuff which is very bad for calculations of durations.
try this:
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = df.parse("14/02/2014");
Date date2 = df.parse("08/03/2014");
int days = Days.daysBetween(date1, date2).getDays();
Try this, by changing return value from millisecond to day.
public static int daysBetween(Date dateFrom, Date dateTo){
return (int)( (dateTo.getTime() - dateFrom.getTime()) / (1000 * 60 * 60 * 24));
}
Start Of Day
If you start with a mid-afternoon date-time object, go back 180 days by calculating seconds * minutes * hours * 180, you'll end up excluding the date-times earlier in that day 180 ago whereas I suppose you would want to include them. You should pay attention to when the day begins.
Time Zone
Both the question and other answers ignore the issue of time zone. Time zone defines the beginning of a day. Given the point about start of day (above), time zone is a related component.
Avoid java.util.Date & .Calendar
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Instead use either Joda-Time or the new java.time package in Java 8.
Joda-Time
Here is some example code using Joda-Time 2.3.
Note that while a Joda-Time DateTime object is similar to a java.util.Date, a DateTime does truly know its own assigned time zone.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTimeInQuestion = new DateTime( 2013, 6, 5, 4, 3, 2, timeZone );
DateTime now = new DateTime( timeZone );
DateTime hundredEightyDaysAgo = now.minusDays( 180 ).withTimeAtStartOfDay();
boolean isExpired = dateTimeInQuestion.isBefore( hundredEightyDaysAgo );
Dump to console…
System.out.println( "dateTimeInQuestion: " + dateTimeInQuestion );
System.out.println( "now: " + now );
System.out.println( "hundredEightyDaysAgo: " + hundredEightyDaysAgo );
System.out.println( "isExpired: " + isExpired );
When run…
dateTimeInQuestion: 2013-06-05T04:03:02.000+02:00
now: 2014-03-10T07:34:26.937+01:00
hundredEightyDaysAgo: 2013-09-11T00:00:00.000+02:00
isExpired: true
How to get the number of milliseconds from October 15th 2011 1:52:34 P.M.
I can get the number of milliseconds from the current time.
Date date = new Date();
long currentTime = date.getTime();
System.out.println("Current time in long: " + currentTime);
long now = System.currentTimeMillis(); // Simpler way to get current time
Date date = new SimpleDateFormat("dd yyyy h:mm:ss a").parse("15 2011 1:52:34 PM");
long timeElapsed = now - date.getTime(); // Here's your number of ms
Use the Calendar API. Then set the month, date and the time you want (October 15, 2011).
To get you started look into this:
Calendar c = Calendar.getInstance();
Hope this helps!
Link
import java.util.Calendar;
import java.util.Date;
public class TimeMilisecond {
public static void main(String[] argv) {
long lDateTime = new Date().getTime();
System.out.println("Date() - Time in milliseconds: " + lDateTime);
Calendar lCDateTime = Calendar.getInstance();
System.out.println("Calender - Time in milliseconds :" + lCDateTime.getTimeInMillis());
}
}
You could use SimpleDateFormat to parse an arbitrariy date and get the difference in ms.
Use java.util.Calendar and fill it with your date information. Then use java.util.Calendar.getTimeInMillis() to get the number of milliseconds since epoch.
I have an application, which needs to compare the time in seconds.
I want to know how to get the current UTC time in seconds.
Can some one post an example of it how can we do this in Java?
You can use this to get timezone passing in timezone you want time back in
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Then you can call whatever you want on the calendar object
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.HOUR));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(cal.get(Calendar.MINUTE));
Below example to compare two calendars in seconds
Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// Set the dates for calendars
cal1.set(2011, 1, 1);
cal2.set(2011, 2, 2);
// Get the represented date in milliseconds as a long
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = milis2 - milis1;
// Calculate difference in seconds
long diffSecs = diff / 1000;
System.out.println("In seconds: " + diffSecs + " seconds");
System.currentTimeMillis()
public static long getUtcTime(long time) {
System.out.println("Time="+time);
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dbefore=new Date(time);
System.out.println("Date before conversion="+format.format(dbefore));
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
TimeZone timezone = c.getTimeZone();
int offset = timezone.getRawOffset();
if(timezone.inDaylightTime(new Date())){
offset = offset + timezone.getDSTSavings();
}
int offsetHrs = offset / 1000 / 60 / 60;
int offsetMins = offset / 1000 / 60 % 60;
System.out.println("offset: " + offsetHrs);
System.out.println("offset: " + offsetMins);
c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
c.add(Calendar.MINUTE, (-offsetMins));
System.out.println("Date after conversion: "+format.format(c.getTime()));
System.out.println("Time converted="+c.getTime().getTime());
return c.getTime().getTime();
}
Joda makes everything simple
import org.joda.time.ReadableInstant;
import org.joda.time.DateTime;
import static org.joda.time.DateTimeZone.UTC;
import static org.joda.time.Seconds.secondsBetween;
...
ReadableInstant start = new DateTime("2011-01-01", UTC);
ReadableInstant end = new DateTime("2011-02-02", UTC);
int secondsDifference = secondsBetween(start, end).getSeconds();
Get current UTC time in seconds (since 1.5) :
TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())
according to Javadoc:
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/System.html#currentTimeMillis
Returns:
the difference, measured in milliseconds, between the current time and
midnight, January 1, 1970 UTC.
To store the date as an integer instead of long, you can divide by 1000 and optionally subtract by another date, such as Jan. 1 2019:
private int getUTC()
{
Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal1.set(2019, 1, 1);
long millis1 = cal1.getTimeInMillis();
//Current date in milliseconds
long millis2 = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
// Calculate difference in seconds
long diff = millis2 - millis1;
return (int)(diff / 1000);
}
This works:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
GregorianCalendar gregorianCalendar = new GregorianCalendar
(
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH),
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
calendar.get(Calendar.SECOND)
);
return gregorianCalendar.getTime();