How to convert timestamp into days ago - java

I have my MySQL database inserting timestamp when I upload a record, so what's entered is something like 2013-02-02 16:59:29. Is there a Java way to convert that into something like 10 Days Ago?

Assuming you've read the datetime value from the database into java:
Date date; // read from database
int days = TimeUnit.MILLISECONDS.toDays(
System.currentTimeMillis() - date.getTime());
then you can format it as you like.

Fetch time from mysql with the help of resultset and pass time data to below method
public static void main(String[] args) {
long timStampFromMysql = rs.getTimestamp("time");// Fetch time from mysql
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(convertTime(timStampFromMysql , 15));
System.out.println(cal);
}
public static long convertTime(long timeInMillies, int days)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeInMillies);
calendar.add(Calendar.DAY_OF_YEAR, days);
return calendar.getTimeInMillis();
}

The Days.daysBetween from the Joda Time library will compute that for you.
DateTime start = new DateTime(time_ms);
DateTime end = new DateTime(now);
Days days = Days.daysBetween(start, end);
int d = days.getDays();

Related

Android - Convert a date into a Timestamp

I have a Date object that I want to convert it back to a Timestamp, the logic behind that is the user can input a event date and then that input gets converted to it's corresponding Timestamp and then uploaded to Firebase Firestore.
I have to use this method to make the sorting easier and accurate, between a list of dates, the nearest one gets displayed to user.
I have the other way around (convert a Timestamp into a date) up and running
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(timestamp * 1000L);
String date = DateFormat.format("dd-MM-yyyy hh:mm:ss", cal).toString();
How to reverse this algorithm to meet my requirements ?
According the documentation of java.util.Calendar.getTimeInMillis() it will return the current time as UTC milliseconds from epoch.
According that, you could do something as
public long dateToTimestamp(Date date) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTime(date);
return cal.getTimeInMillis() / 1000L;
}
I've tested and it works perfectly.
class Main {
public static long dateToTimestamp(Date date) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTime(date);
return cal.getTimeInMillis() / 1000L;
}
public static Date timeStampToDate(long timestamp) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(timestamp * 1000L);
return cal.getTime();
}
public static void main(String[] args) {
long date = 1000;
System.out.println("Time as Date: " + timeStampToDate(date));
System.out.println("Time in timestamp: " + dateToTimestamp(timeStampToDate(date)));
}
}
One test case that tests that the method really does the opposite than the one that you've in the question:
#Test
void testTimestampConversion() {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
// Present
long expected = dateToTimestamp(cal.getTime());
assertEquals(expected, dateToTimestamp(timeStampToDate(expected)));
// Past
long expectedPast = 1000;
assertEquals(expectedPast, dateToTimestamp(timeStampToDate(expectedPast)));
// Future
Date future = cal.getTime();
future.setYear(3000);
long expectedFuture = dateToTimestamp(future);
assertEquals(expectedFuture, dateToTimestamp(timeStampToDate(expectedFuture)));
}

Wrong value of Days between two Dates

I'm trying to count the days between two dates but I can't get a right result.
I did the same that someone described to me.
My result should be an int or long. For this example I would expext 11 but 10 is also fine.
That's the code:
String startDate = "2018-03-25";
String endDate = "2018-04-05";
Date startDate1 = stringToDate(startDate);
Date endDate1 = stringToDate(endDate);
long ab = daysBetween(startDate1, endDate1);
String ab1 = String.valueOf(ab);
And that's the methods:
public static long daysBetween(Date startDate, Date endDate) {
Calendar sDate = getDatePart(startDate);
Calendar eDate = getDatePart(endDate);
long daysBetween = 0;
while (sDate.before(eDate)) {
sDate.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
public Date stringToDate(String stringDatum) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = format.parse(stringDatum);
return date;
}
catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static Calendar getDatePart(Date date){
Calendar cal = Calendar.getInstance(); // get calendar instance
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0); // set hour to midnight
cal.set(Calendar.MINUTE, 0); // set minute in hour
cal.set(Calendar.SECOND, 0); // set second in minute
cal.set(Calendar.MILLISECOND, 0); // set millisecond in second
return cal; // return the date part
}
java.util.Date, Calendar and SimpleDateFormat are part of a terrible API. They make the job of date/time handling harder than it already is.
Make yourself a favor and use a decent date/time library: https://github.com/JakeWharton/ThreeTenABP - here's a nice tutorial on how to use it - How to use ThreeTenABP in Android Project
With this API, it's so easy to do what you want:
LocalDate startDate = LocalDate.parse("2018-03-25");
LocalDate endDate = LocalDate.parse("2018-04-05");
long daysBetween = ChronoUnit.DAYS.between(startDate, endDate); // 11
I've chosen to use LocalDate based on your code: the inputs have only day, month and year, and you're setting the hour/minute/seconds to zero, so I understand that you don't care about the time of the day to calculate the difference - which makes LocalDate the best choice.
Date and Calendar represent a specific point in time, and Calendar also uses a timezone, so Daylight Saving changes might affect the results, depending on the device's default timezone. Using a LocalDate avoids this problem, because this class doesn't have a timezone.
But anyway, I've tested your code and also got 11 as result, so it's not clear what problems you're facing.
private static long daysBetween(Date date1, Date date2){
return (date2.getTime() - date1.getTime()) / (60*60*24*1000);
}

Set new time after the actual one

I'm trying to create a method that prints e.g. actual time of arrival (now) and then it prints the time of departure which I want to set plus 3 minutes compared to the first one.
public void updateTimes(){
SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
this.arrivalTime = new Date();
this.departureTime = this.arrivalTime.plusMinutes(3);
}
Departure time doesn't work as intended.
Any help is welcome.
java.util.Date not have plusMinutes.
It can be better if you use Java 8, with java.time library :
LocalTime arrivalTime = LocalTime.now();//Current time
LocalTime departureTime = arrivalTime.plusMinutes(3);//plus 3 minutes to the time
//Then you can format the time
String result = departureTime.format(DateTimeFormatter.ofPattern("H:mm"));
Another solution using Calendar looks like:
Calendar cal = Calendar.getInstance();
cal.setTime(arrivalTime); // only if different from "now"
cal.add(Calendar.MINUTE, 3);
departureTime = cal.getTime();
I think you can do something like below:
SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
Date date = new Date();
System.out.println("arrival time = " + sdf.format(date));
int min = date.getMinutes();
date.setMinutes(min+3);
System.out.println("departure time = " + sdf.format(date));

Java get current day from unix timestamp [duplicate]

This question already has answers here:
Java: Date from unix timestamp
(11 answers)
Closed 5 years ago.
I want to convert unix timestamp to only the current day, like the current day of the month of current day of the year, is it possible to do only using math, like *, /, or something?
The short solution is something like
long epoch = 1501350790; // current unix time
int day = Integer.parseInt(new SimpleDateFormat("dd").format(new Date(epoch * 1000L)));
it is possible to get this result by calculation (* and /) but there is no easy way. you can use the implementation of java.util.GregorianCalendar as reference
You can use SimpleDateFormat to format your date:
long unixSeconds = 1372339860;
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4")); // give a timezone reference for formating (see comment at the bottom
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
You can also convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
After doing it, you can get what you want:
Calendar cal = Calendar.getInstance();
cal.setTime(dateTime);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); //here is what you need
int day = cal.get(Calendar.DAY_OF_MONTH);
You can calculate the date from a unix timestamp with java.util.Date
You need to multiply the timestamp with 1000, because java expects milliseconds. You can use the cal.get(Calendar.DAY_OF_MONTH) function to print the day.
import java.sql.Timestamp;
import java.util.Calendar;
public class MyFirstJavaProgram {
public static void main(String []args) {
long unixTimeStamp= System.currentTimeMillis() / 1000L;
java.util.Date time=new java.util.Date((long)unixTimeStamp*1000);
Calendar cal = Calendar.getInstance();
// It's a good point better use cal because date-functions are deprecated
cal.setTime(time);
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
}
}
Any further questions please leave a comment.

How to calculate remaining days?

private long calculateRemainingDays() {
final Calendar c = Calendar.getInstance();
c.set(2015, 7, 23);
final Calendar today = Calendar.getInstance();
final long millis = c.getTimeInMillis()
- today.getTimeInMillis();
// Convert to days
final long days = millis / 86400000;
return days;
}
I need to add a function in my android application. I want a remaining days from current day to 2015/9/30. When the date is change to next day, the remaining days will decrease. I would like to say like that:
7 days remaining... 6/5/4/etc... Please help me to get correct remaining days. Sorry for my poor english. Thanks!
Use Calender.JULY instead of 7 in the parameters for the set() method.
7 = August.
6 = July.
As it starts with January as 0. It's better to use the static instance variables like Calender.JANUARY.
But as you want to calculate till 2015/9/30, you should set the value as
c.set(2015, Calender.SEPTEMBER, 09);
The rest of the code seems ok. It will return the correct number of days.
Try this :-
final long millis = c.getTimeInMillis()
- today.getTimeInMillis();
System.out.println ("Days: " + TimeUnit.DAYS.convert(millis , TimeUnit.MILLISECONDS));
if you don't mind using joda.time
you can do something of this form:
final Calendar c = Calendar.getInstance();
c.set(2015, Calender.SEPTEMBER, 30);
Date endDate = c.getTime();
Instant startInstant = new Instant(new Date());
Instant endInstant = new Instant(endDate);
Days days = Days.daysBetween(startInstant, endInstant);

Categories