Change the session time - java

i need to add more time session life time . but cant add more 10-12 days
/**
* Logs in the user by saving user details and setting session
*
* #param username
* #param fullName
*/
public void loginUser(String username, String fullName) {
mEditor.putString(KEY_USERNAME, username);
mEditor.putString(KEY_FULL_NAME, fullName);
Date date = new Date();
//Set user session for next 7 days
long millis = date.getTime() + (30 * 24 * 60 *60 * 1000);
mEditor.putLong(KEY_EXPIRES, millis);
mEditor.commit();
}

You can use the actual value of the milliseconds you want. Convert from days to milliseconds for instance, in a clearer way.
long millis = date.getTime() + TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS);
//this will add 30 days
You can change the 30 to whatever days you'd prefer.

Related

Android (Java): Calculate age with the help of DOB and birth time

I have tried it with EditText which will receive value of datepicker and timepicker and will display the birthdate and birth time but now I don't know how to calculate age from the date and time.
First get today date
Date today = new Date();
Get difference in time
long timeDiff = today.getTime() - DOB.getTime();
Now you can convert time to DATE, MONTH, or YEAR
int numOfDays = (int) (timeDiff / (1000 * 60 * 60 * 24));
double years = 0.00273973 * numOfDays;

Android - Get Unix time stamp for beginning and end of day

I have an SQLite database that has an integer column to store a unix time stamp and I need to be able to query this column for specific days.
I am looking for a method to return the Unix time for the beginning and end of a given day. What is the best way to do this?
Here is one way to do it.
public long getStartOfDayInMillis() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
public long getEndOfDayInMillis() {
// Add one day's time to the beginning of the day.
// 24 hours * 60 minutes * 60 seconds * 1000 milliseconds = 1 day
return getStartOfDayInMillis() + (24 * 60 * 60 * 1000);
}
If you want the times for a specific date, you can modify the code to handle that.
/**
* #param date the date in the format "yyyy-MM-dd"
*/
public long getStartOfDayInMillis(String date) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(format.parse(date));
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/**
* #param date the date in the format "yyyy-MM-dd"
*/
public long getEndOfDayInMillis(String date) throws ParseException {
// Add one day's time to the beginning of the day.
// 24 hours * 60 minutes * 60 seconds * 1000 milliseconds = 1 day
return getStartOfDayInMillis(date) + (24 * 60 * 60 * 1000);
}

Android date picker calculation , before and after a specific date

I have an application which use the current date and a date that is chose by user using date picker as follow:
If the date that the user chose is more than the current date +280 day,
some code will be executed.
If the date that the user chose is less than the current date , some
code will be executed.
I used this code to do so ..
Calendar start2 = Calendar.getInstance();
int birthYear = birthDayDatePicker.getYear();
int birthMonth = birthDayDatePicker.getMonth();
int birthDay = birthDayDatePicker.getDayOfMonth();
start2.set(birthYear, birthMonth, birthDay);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(birthDate);
cal2.add(Calendar.DAY_OF_MONTH,daysToAdd);
birthDayChosenCalender.set(birthYear,birthMonth,birthDay);
MaxBirthDayCalender.set(currentYear, currentMonth, currentDay);
long diff = birthDayChosenCalender.getTimeInMillis() - MaxBirthDayCalender.getTimeInMillis(); //result in millis
long daysBetween = diff / (24 * 60 * 60 * 1000);
System.out.println("Days between ,,,,,,,,,,,,,,,,,,"+daysBetween);
if(MaxBirthDayCalender.before(birthDayChosenCalender) && daysBetween <= 280){
do sth }
Is there any other clean way to do that ! because this way is not working well !
The other clean way to do it is to use the Joda Time library.
Other than that, everything can be done using millis and a single calendar instance:
Calendar pickedDate = new GregorianCalendar(
picker.getYear(),
picker.getMonth(),
picker.getDayOfMonth());
long pickedTime = pickedDate.getTimeInMillis();
long now = new Date().getTime();
if (pickedTime - now <= (280 * 24 * 60 * 60 * 1000)) { // 280 days in milliseconds
// ...
}
Should cover the requirement:
I have an application which use the current date and a date that is chose by user using date picker as follow:
If the date that the user chose is more than the current date +280 day, some code will be executed.
If the date that the user chose is less than the current date , some code will be executed.

find hour or minute difference between 2 java.sql.Timestamps?

I store a java.sql.Timestamp in a postgresql database as Timestamp data type and I want to find out the difference in minutes or hours from the one stored in the DB to the current timestamp. What is the best way about doing this? are there built in methods for it or do I have to convert it to long or something?
I ended using this, just want to post it for others if they search for it.
public static long compareTwoTimeStamps(java.sql.Timestamp currentTime, java.sql.Timestamp oldTime)
{
long milliseconds1 = oldTime.getTime();
long milliseconds2 = currentTime.getTime();
long diff = milliseconds2 - milliseconds1;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
return diffMinutes;
}
Use the UNIX_TIMESTAMP function to convert the DATETIME into the value in Hour, minutes and seconds.
And if you are not sure of which value is bigger then use the ABS function.
For date add/remove this is my generic function :
public static Date addRemoveAmountsFromDate(Date date, int field, int amount) {
Calendar tempCalendar = Calendar.getInstance();
tempCalendar.setTime(date);
tempCalendar.add(field, amount);
return tempCalendar.getTime();
}
example for "field" : Calendar.HOUR_OF_DAY, Calendar.MINUTE
Just use:
Date.compareTo(Date)
You have to convert java.sql.Timestamps to Date first.
date_part function can give you hours or as the interest may be but, it is a kind of substr and hence can't rely on it. You need to convert your timestamp value into unix_timestamp and extract total elapsed number of hours, minutes or whatever relevant since your timestamp till current_timestamp.
Example:
select age( now(), timestamp '2010-11-12 13:14:15' );
//results the interval to be "*1 year 6 mons 2 days 04:39:36.093*"
select date_part( 'hours', age( now(), timestamp '2010-03-10 02:03:04' ) );
// results *4* which is not correct.
Correct value of hours or others can be calculated after finding total number of seconds elapsed since 1970. This can be achieved using epoch with extract function.
epoch returns total number of seconds since 1970-01-01 00:00:00-00. And, you know, we can convert it into hours by dividing it with 3600.
Using epoch with extract:
select
EXTRACT( EPOCH FROM current_timestamp - timestamp '2010-11-12 13:14:15' ) as total_seconds,
EXTRACT( EPOCH FROM current_timestamp - timestamp '2010-11-12 13:14:15' ) / 3600 as total_hours;
ROUND(
EXTRACT( EPOCH FROM current_timestamp - timestamp '2010-11-12 13:14:15' ) / 3600
) as total_hours_rounded;
// results:
----------------+--------------+-----------------------
| total_seconds | total_hours | total_hours_rounded |
| --------------+--------------+----------------------|
| 47452282.218 | 13181.189505 | 13181 |
----------------+--------------+-----------------------
Similarly, we can extract other required values and use as required.
Use this, It is extremely accurate :
long diff = end - start;
long diffDays = diff / (24 * 60 * 60 * 1000);
long remain = diff % (24 * 60 * 60 * 1000);
long diffHours = remain / (60 * 60 * 1000);
remain = remain % (60 * 60 * 1000);
long diffMinutes = remain / (60 * 1000);
remain = remain % (60 * 1000);
long diffSeconds = remain / (1000);
System.out.println("days : " + diffDays);
System.out.println("hours : " + diffHours);
System.out.println("minutes : " + diffMinutes);
System.out.println("secs: " + diffSeconds2);
So the answer to this is pretty ancient and it came up when I was searching for an elegant solution.
There is a much nicer way to do this without having to faff with millisecond conversions:
long totalHours = ChronoUnit.HOURS.between(startTime.toInstant(), endTime.toInstant());
long totalMinutes = ChronoUnit.MINUTES.between(startTime.toInstant(), endTime.toInstant());
long totalSeconds = ChronoUnit.SECONDS.between(startTime.toInstant(), endTime.toInstant());
And a bunch of others MILLIS, YEARS, DAYS, HALF_DAYS, DECADES, CENTURIES and more!
Only thing I'm not sure about is if these longer units account for leap years and you may need to apply some changes if you want to account for time zones and DST.
Enjoy.

Java difference of currentTimeMillis() Function and special date - MySQL?

I have 50000 XML records like this in the database:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<urlMD5>11ca7070ad6eb3180c53281e7b597976</urlMD5>
<date>
<year>2011</year>
<month>8</month>
<day>6</day>
<h>19</h>
<m>26</m>
<s>40</s>
</date>
<enc>utf-8</enc>
</root>
as you see, I saved the date in separated format.
Now I need to extract the currentTimeMillis() of these days and save to database in new field.
So I can easily compare them with current currentTimeMillis() and find out which document have been stored in last two days.
for example:
int ct = currentTimeMillis();
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/crawler?" + "user=root&password=&useUnicode=true&characterEncoding=UTF-8");
Statement stat = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM DBName WHERE ct - 60 * 60 * 24 * 2 > timeField");
And because I want to use this field for so many times, I want to use a simple query and I don't want to extract the XML format each time.
The problem is currentTimeMillis() function calculate currentTimeMillis that passed from January 1, 1970 and I need to calculate the same thing with my data.
I have written following code with the same code that I used before to store XML data to make sure if I can do it or not:
int s = 0;
s += (Calendar.getInstance().get(Calendar.YEAR) - 1970) * 60 * 60 * 24 * 365;
s += (Calendar.getInstance().get(Calendar.MONTH)) * 60 * 60 * 24 * 31;
s += (Calendar.getInstance().get(Calendar.DAY_OF_MONTH) * 60 * 60 * 24);
s += (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) * 60 * 60);
s += (Calendar.getInstance().get(Calendar.MINUTE) * 60);
s += (Calendar.getInstance().get(Calendar.SECOND));
System.out.println(s);
System.out.println(System.currentTimeMillis() / 1000);
but the results are not the same:
1312313680
1312643080
One of the reasons is because not every month have 31 days.
Any way, I need help to find out how can I calculate the currentTimeMillis with special date, not the current date?
I should mention that I am using mysql, so maybe I can save the dates in special format that I can compare the with SQL query?
Use the set method of Calendar:
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
etc.
And then extract the number of milliseconds with c.getTime().getTime().

Categories

Resources