This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calculate date/time difference in java
how would a future date such as Sat Feb 17 2012 be converted into milliseconds in java that can then be subtracted from the current time in milliseconds to yield time remaining until that future date.
The simplest technique would be to use DateFormat:
String input = "Sat Feb 17 2012";
Date date = new SimpleDateFormat("EEE MMM dd yyyy", Locale.ENGLISH).parse(input);
long milliseconds = date.getTime();
long millisecondsFromNow = milliseconds - (new Date()).getTime();
Toast.makeText(this, "Milliseconds to future date="+millisecondsFromNow, Toast.LENGTH_SHORT).show();
A more difficult technique (that basically does what DateFormat does for you) involves parsing it yourself (this would not be considered best practice):
String input = "Sat Feb 17 2012";
String[] myDate = input.split("\\s+");
int year = Integer.parseInt(myDate[3]);
String monthString = myDate[1];
int mo = monthString.equals("Jan")? Calendar.JANUARY :
monthString.equals("Feb")? Calendar.FEBRUARY :
monthString.equals("Mar")? Calendar.MARCH :
monthString.equals("Apr")? Calendar.APRIL :
monthString.equals("May")? Calendar.MAY :
monthString.equals("Jun")? Calendar.JUNE :
monthString.equals("Jul")? Calendar.JULY :
monthString.equals("Aug")? Calendar.AUGUST :
monthString.equals("Sep")? Calendar.SEPTEMBER :
monthString.equals("Oct")? Calendar.OCTOBER :
monthString.equals("Nov")? Calendar.NOVEMBER :
monthString.equals("Dec")? Calendar.DECEMBER : 0;
int day = Integer.parseInt(myDate[2]);
Calendar c = Calendar.getInstance();
c.set(year, mo, day);
long then = c.getTimeInMillis();
Time current_time = new Time();
current_time.setToNow();
long now = current_time.toMillis(false);
long future = then - now;
Date d = new Date(future);
//TODO use d as you need.
Toast.makeText(this, "Milliseconds to future date="+future, Toast.LENGTH_SHORT).show();
Firts, you must parse you String to get its Date representation. Here are examples and some docs.
Then you shoud call getTime() method of your Date.
DateFormat format = new SimpleDateFormat("EEE MMM dd yyyy", Locale.US);
long futureTime = 0;
try {
Date date = format.parse("Sat Feb 17 2012");
futureTime = date.getTime();
} catch (ParseException e) {
Log.e("log", e.getMessage(), e);
}
long curTime = System.currentTimeMillis();
long diff = futureTime - curTime;
Pass year, month and day of the future date in the date of this code and variable diff will give the millisecond time till that date,
Date date = new GregorianCalendar(year, month, day).getTime();
Date today = new Date();
long diff = date.getTime() - today.getTime();
You can simply call the getTime() method of date object. please follow through the sample below
import java.util.Date;
public class Test {
#SuppressWarnings("deprecation")
public static void main(String[] args) {
System.out.println(new Date("Sat Feb 17 2012").getTime());
}
}
try { String str_date="11-June-07";
SimpleDateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MMM-yy");
date = (Date) formatter.parse(str_date);
Log.i("test",""+date);
} catch (Exception e)
{System.out.println("Exception :"+e); }
Date d = new Date();
long time = d.getTime();
long timeDiff = time - lastTime;
//timeDiff will contain your value.
//import these two,
//import java.text.SimpleDateFormat;
//import java.util.Date;
Related
I have a Date object in Java stored as Java's Date type.
I also have a Gregorian Calendar created date. The gregorian calendar date has no parameters and therefore is an instance of today's date (and time?).
With the java date, I want to be able to get the year, month, day, hour, minute, and seconds from the java date type and compare the the gregoriancalendar date.
I saw that at the moment the Java date is stored as a long and the only methods available seem to just write the long as a formatted date string. Is there a way to access Year, month, day, etc?
I saw that the getYear(), getMonth(), etc. methods for Date class have been deprecated. I was wondering what's the best practice to use the Java Date instance I have with the GregorianCalendar date.
My end goal is to do a date calculation so that I can check that the Java date is within so many hours, minutes etc of today's date and time.
I'm still a newbie to Java and am getting a bit puzzled by this.
Use something like:
Date date; // your date
// Choose time zone in which you want to interpret your Date
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
// etc.
Beware, months start at 0, not 1.
Edit: Since Java 8 it's better to use java.time.LocalDate rather than java.util.Calendar. See this answer for how to do it.
With Java 8 and later, you can convert the Date object to a LocalDate object and then easily get the year, month and day.
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
Note that getMonthValue() returns an int value from 1 to 12.
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
simpleDateFormat = new SimpleDateFormat("MMMM");
System.out.println("MONTH "+simpleDateFormat.format(date).toUpperCase());
simpleDateFormat = new SimpleDateFormat("YYYY");
System.out.println("YEAR "+simpleDateFormat.format(date).toUpperCase());
EDIT: The output for date = Fri Jun 15 09:20:21 CEST 2018 is:
DAY FRIDAY
MONTH JUNE
YEAR 2018
You could do something like this, it will explain how the Date class works.
String currentDateString = "02/27/2012 17:00:00";
SimpleDateFormat sd = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date currentDate = sd.parse(currentDateString);
String yourDateString = "02/28/2012 15:00:00";
SimpleDateFormat yourDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date yourDate = yourDateFormat.parse(yourDateString);
if (yourDate.after(currentDate)) {
System.out.println("After");
} else if(yourDate.equals(currentDate)) {
System.out.println("Same");
} else {
System.out.println("Before");
}
private boolean isSameDay(Date date1, Date date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date2);
boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
return (sameDay && sameMonth && sameYear);
}
It might be easier
Date date1 = new Date("31-May-2017");
OR
java.sql.Date date1 = new java.sql.Date((new Date()).getTime());
SimpleDateFormat formatNowDay = new SimpleDateFormat("dd");
SimpleDateFormat formatNowMonth = new SimpleDateFormat("MM");
SimpleDateFormat formatNowYear = new SimpleDateFormat("YYYY");
String currentDay = formatNowDay.format(date1);
String currentMonth = formatNowMonth.format(date1);
String currentYear = formatNowYear.format(date1);
Date queueDate = new SimpleDateFormat("yyyy-MM-dd").parse(inputDtStr);
Calendar queueDateCal = Calendar.getInstance();
queueDateCal.setTime(queueDate);
if(queueDateCal.get(Calendar.DAY_OF_YEAR)==Calendar.getInstance().get(Calendar.DAY_OF_YEAR))
{
"same day of the year!";
}
#Test
public void testDate() throws ParseException {
long start = System.currentTimeMillis();
long round = 100000l;
for (int i = 0; i < round; i++) {
StringUtil.getYearMonthDay(new Date());
}
long mid = System.currentTimeMillis();
for (int i = 0; i < round; i++) {
StringUtil.getYearMonthDay2(new Date());
}
long end = System.currentTimeMillis();
System.out.println(mid - start);
System.out.println(end - mid);
}
public static Date getYearMonthDay(Date date) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat("yyyyyMMdd");
String dateStr = f.format(date);
return f.parse(dateStr);
}
public static Date getYearMonthDay2(Date date) throws ParseException {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.HOUR_OF_DAY, 0);
return c.getTime();
}
public static int compare(Date today, Date future, Date past) {
Date today1 = StringUtil.getYearMonthDay2(today);
Date future1 = StringUtil.getYearMonthDay2(future);
Date past1 = StringUtil.getYearMonthDay2(past);
return today.compare // or today.after or today.before
}
getYearMonthDay2(the calendar solution) is ten times faster. Now you have yyyy MM dd 00 00 00, and then compare using date.compare
This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
Reason is, you are not subtracting two dates with same time format.
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Why not use LocalDate?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}
The problem is that
Date createdDate = new Date();
sets createdDate to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00.
Let's say you ran this at exactly 18:00 local time, you end up with
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
You should be using the newer java.time.* classes from Java 8. There is a class LocalDate that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now() to get the current date, as well as methods for calculating intervals between LocalDate instances.
Using the Calendar.get(Calendar.DAY_OF_MONTH) as pointed out by python:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);
I would like to calculate the time difference between two days (e.g. Friday and Saturday) of the same week. This sort of calculation is required for validating a time restriction of my project. To understand more about the restriction see the below examples,
Example 1
{
"id": "3",
"from_day": "Fri",
"from_time": "16:00:00",
"to_day": "Sat",
"to_time": "06:00:00"
}
Example 2
{
"id": "4",
"from_day": "Mon",
"from_time": "04:00:00",
"to_day": "Mon",
"to_time": "09:00:00"
}
From the above example I've to verify if the running application passes between the exact date and time of the same week.
What I've done so far?
I've created this simple function which takes the "day of week" e.g Mon, "from time" e.g 04:00:00 and "to time" e.g 09:00:00 as parameter and returns if it's within the range.
public boolean getValidity(String day, String dateStart, String dateStop) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
String current_day = new SimpleDateFormat("EE", Locale.ENGLISH)
.format(date.getTime());
if (current_day.matches(day)) {
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
Date today = Calendar.getInstance().getTime();
String datePresent = format.format(today);
Date d1 = null;
Date d2 = null;
Date d3 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
d3 = format.parse(datePresent);
} catch (Exception e) {
e.printStackTrace();
}
long current_time = d3.getTime();
long start_time = d1.getTime();
long stop_time = d2.getTime();
if (current_time >= start_time && current_time <= stop_time) {
return true;
} else {
return false;
}
}
return false;
}
// this function is used for converting the time into GMT +8 before passing as a parameter in the getValidity() function
public String toGMT(String time){
//first convert the received string to date
Date date = null;
//creating DateFormat for converting time from local timezone to GMT
DateFormat format = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
try {
date = format.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
//getting GMT timezone, you can get any timezone e.g. UTC
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
return format.format(date).toString();
}
But the above code doesn't works for the first example where the dates are different. It would be extremely helpful if anyone can give some idea of solving the issue.
You can turn a date object into a long (milliseconds since Jan 1, 1970), and then use TimeUnit to get the number of seconds:
long diffInMs = endDate.getTime() - startDate.getTime();
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);
end date and start date as date object for your days which you can do self.
I am trying to get time difference between dates as String format like 4 hours ago.
Here is my code
To my understanding Calendar.getInstance() gives time as GMT. my server time is GMT so the difference should be GMT Vs GMT however the difference with this code is GMT (Server) Vs. GMT +5 ( My Current timezone)
How can i make the difference GMT only?
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date convertedDate = new Date();
Calendar systemCal = Calendar.getInstance();
long currentTime = systemCal.getTimeInMillis();
/***********************************/
Calendar cal = Calendar.getInstance();
try {
convertedDate = dateFormat.parse(dateString);
} catch (Exception e) {
return "";
}
cal.setTime(convertedDate);
/***********************************/
CharSequence myDateString = DateUtils.getRelativeTimeSpanString(cal.getTimeInMillis(), currentTime, DateUtils.MINUTE_IN_MILLIS);
return myDateString.toString();
Try following codes. It demonstrates clearly on how to parse a String datetime to GMT timezone. Key point is the first line which sets the default timezone.
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
try {
Date convertedDate = dateFormatGmt.parse("2015-01-29 10:05:00");
long diffSeconds = (cal.getTimeInMillis() - convertedDate.getTime()) / 1000;
System.out.println("convertedDate: " + convertedDate);
System.out.println("current: " + cal.getTime());
System.out.println("Difference in seconds: " + diffSeconds);
}
catch (Exception e) {
e.printStackTrace();
}
The Calendar.getInstance() return the time zone the computer is set to. So unless you always have control over that i would advice using the getInstance(TimeZone zone) method.
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#getInstance%28java.util.TimeZone%29
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
But if you want a easier way to do it i would advice to look in to joda time.
http://www.joda.org/joda-time/
This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 8 years ago.
I have a object that giving date and time in this format "2014-06-11 16:32:36.828".
I want to remove millisec .828.
In my db that object is in time stamp format but whenever i am showing i am converting it to tostring().
so how to remove millisec please help me
The following code convert "2014-06-11 16:32:36.828" into "2014-06-11 16:32:36"
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2014-06-11 16:32:36.828"));
Explanation:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2014-06-11 16:32:36.828") parse the input string into
Wed Jun 11 16:32:36 IST 2014
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) format the input date into specified structure.
I would use DateUtils.truncate(date, Calendar.SECOND)
Date d = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(yourString);
Calendar c = Calendar.getInstance();
c.setTime(d);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
I remember there is a way to directly read Date off your timestamp field but I don't do that in my everyday coding. So I'd left for others to post so. Nevertheless, you can use the same above code to translate your date from that timestamp into a date without MILLISECOND.
If you receive it as a Timestamp, you should use the appropriate formatter when converting it to a string:
String s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
Note: this will use the default time zone of the local computer.
Extract epoch millis from the original Date object and do integer division by 1000 followed by multiplication by 1000. Create Date object with the time zone of the original object and the millis calculated the above suggested way.
You can get the system time as follows without milliseconds
import java.text.SimpleDateFormat;
import java.util.Calendar;
And the code
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter= new SimpleDateFormat("dd-MM-YYYY-hh:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
System.out.println(dateNow);
if you want to mantain the format try something like that:
public static String getFechaTimestampToString (Timestamp timestamp) {
String date = "";
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(timestamp.getTime()));
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DAY_OF_MONTH);
String monthstr = "";
String daystr = "";
if(month<10)
monthstr = "0"+month;
else
monthstr = ""+month;
if(day<10)
daystr = "0"+day;
else
daystr = ""+day;
date = year + "-" + monthstr + "-" + daystr ;
return date;
}
To reverse data to database:
public static Timestamp getFechaStringToTimestamp (String strDate) {
Timestamp timestamp = null;
strDate = strDate + " 00:00:00";
timestamp = Timestamp.valueOf(strDate);
return timestamp;
}