In my app I have 3 edittexts where user enters day (f.e. 23), month (f.e. 09) and year (f.e. 2008).
I would like to know how to determine is user younger or older than 18 years.
How to do this?
PS. Please write your solution in Kotlin
Try this code. I have not tested it but It will give you the desired output. Let me know If not
private int getYears() {
int year = 2008; // get from the year edittext
int month = 9; // get from the month edittext
int day = 23; // get from the date edittext
Calendar c1 = Calendar.getInstance();
c1.set(year, month - 1, day, 0, 0); // as MONTH in calender is 0 based.
Calendar c2 = Calendar.getInstance();
int diff = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
if (c1.get(Calendar.MONTH) > c2.get(Calendar.MONTH) ||
(c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) && c1.get(Calendar.DATE) > c2.get(Calendar.DATE))) {
diff--;
}
return diff;
}
And here is an equivalent Kotlin funtion
private fun getYears(): Int {
val year = 2008 // get from the year edittext
val month = 9 // get from the month edittext
val day = 23 // get from the date edittext
val c1 = Calendar.getInstance()
c1[year, month - 1, day, 0] = 0 // as MONTH in calender is 0 based.
val c2 = Calendar.getInstance()
var diff = c2[Calendar.YEAR] - c1[Calendar.YEAR]
if (c1[Calendar.MONTH] > c2[Calendar.MONTH] ||
c1[Calendar.MONTH] == c2[Calendar.MONTH] && c1[Calendar.DATE] > c2[Calendar.DATE]
) {
diff--
}
return diff
}
This is the correct solutions to your problem, I hope this will help you
and please import these lines also
import java.time.LocalDate
import java.time.Period
import java.util.Locale
fun isUser18Older(): Boolean {
val todaysDate = LocalDate.now()
val userDob = LocalDate.of(2004, 2, 3) //3-Feb-2004
val yearDiff = Period.between(userDob,todaysDate ).years
return yearDiff >= 18
}
In age control, leap years can confuse our calculations. For this reason, I prepared an algorithm in the simplest way. You can use this extension method without any problems with year, month, day comparisons.
fun Date.isUser18Older(): Boolean {
val toDate = Calendar.getInstance()
val birthDate = Calendar.getInstance()
birthDate.time = this
if (toDate.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR) > 18) {
return true
}
if (toDate.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR) == 18) {
if (toDate.get(Calendar.MONTH) > birthDate.get(Calendar.MONTH)) {
return true
}
if (toDate.get(Calendar.MONTH) == birthDate.get(Calendar.MONTH) && birthDate.get(Calendar.DAY_OF_MONTH) <= toDate.get(
Calendar.DAY_OF_MONTH
)
) {
return true
}
}
return false
}
Ref: 1.https://stackoverflow.com/questions/25460965/how-can-i-create-a-date-object-with-a-specific-format
2.https://stackoverflow.com/questions/10690370/how-do-i-get-difference-between-two-dates-in-android-tried-every-thing-and-pos/63207518
I would suggest doing this in a step-by-step approach.
Convert the data to a string in dd/mm/yyyy format
Now create a date object with that in this fashion
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Date d= new Date(); //Get system date
//Convert Date object to a string
String strDate = sdf.format(d);
//Convert a String to Date
d = sdf.parse("02/04/2014");
Find the difference between the dates using the following format
long diffInMillisec = date1.getTime() - date2.getTime();
long diffInDays = TimeUnit.MILLISECONDS.toDays(diffInMillisec);
long diffInHours = TimeUnit.MILLISECONDS.toHours(diffInMillisec);
long diffInMin = TimeUnit.MILLISECONDS.toMinutes(diffInMillisec);
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec);
Convert to years and then check
numyears = Math.floor(diffInSec/ 31536000)
if(numyears>18){
//your code here
}
This is the kotlin implementation of the answerr given by #Bhargav
private fun getUserYears() : Int {
var year = 2003; // get from the year edittext
var month = 4; // get from the month edittext
var day = 30; // get from the date edittext
var c1 = Calendar.getInstance ();
c1.set(year, month - 1, day, 0, 0); // as MONTH in calender is 0 based.
var c2 = Calendar.getInstance();
var diff = c2.get (Calendar.YEAR) - c1.get(Calendar.YEAR);
if (c1.get(Calendar.MONTH) > c2.get(Calendar.MONTH) ||
(c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) && c1.get(Calendar.DATE) > c2.get(
Calendar.DATE
))
) {
diff--;
}
return diff;
}
Related
So started learning Kotlin and Android studio coding.
I was following Youtube video
https://www.youtube.com/watch?v=z3_QgdmXGK4&t=994s&ab_channel=Dr.ParagShukla
I am making simple age calculator, however, cant make string to become date, so i could subtract input date with current date. Code looks exactly same as in the video.
Code compiles well and gets installed in android device, however, whenever press Calculate Age button, app stops responding because of var dob = sdf.parse(dob) function. I assume it cant convert the date from string to date format for further calculations. Thanks.
Code below:
fun openDatePicker(view: View) {
var c = Calendar.getInstance()
DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener { datePicker, yy, mm, dd -> // listens what date picker has to say
var mm = mm + 1
var date = "$dd/ $mm /$yy "
TimePickerDialog(
this,
TimePickerDialog.OnTimeSetListener { timePicker, hh, mi ->
date += " $hh:$mi"
editTextTextPersonName.setText(date) // shows date in the line
},
c.get(Calendar.HOUR_OF_DAY),
c.get(Calendar.MINUTE),
true
).show()
}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)
).show()
}
fun Calculateage(view: View) {
var today = Date() // todays date
var dobs = editTextTextPersonName.text.toString() // takes value from input
var sdf = SimpleDateFormat("mm/MM/yy HH:mm")
var dob = sdf.parse(dobs) // converts the date to simple date, no can find difference
var days = (today.time - dob.time) / 86400000 // converts into mil secs, need to divide by milsecs in a day
var hours = (today.time - dob.time) % 86400000 / 3600000
var minutes = (today.time - dob.time) % 86400000 % 3600000 / 60000
var sec = (today.time - dob.time) % 86400000 % 3600000 % 60000/1000
textView.visibility = View.VISIBLE
textView.setText("Days = $days\nHours= $hours\nMinutes=$minutes\nSeconds = $sec")
}
Your SimpleDateFormat doesn't match your string value.
Your var date looks like var date = "$dd/ $mm /$yy $hh:$mi"
Your SimpleDateFormat has "mm/MM/yy HH:mm"
You should change your formatter to something like this:
"dd/ MM /yy HH:mm"
My week start from Friday and end from Thursday, and i get a list of weeks of current month weeks.
In my Code every thing working fine but get current month four weeks but i want previous four weeks not next weeks of current week.
public void getWeeksOfMonth( int year) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
Calendar cal = Calendar.getInstance();
int currentmonth = cal.get(Calendar.MONTH);
int val = 0;
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, currentmonth);
cal.set(DAY_OF_MONTH, 1);
int ndays = cal.getActualMaximum(DAY_OF_MONTH);
System.out.println(ndays + "<<<ff");
while (cal.get(DAY_OF_WEEK) != FRIDAY) {
cal.add(DAY_OF_MONTH, 1);
ndays--;
}
int remainingDays = ndays % 7;
if (remainingDays == 0)
ndays += 7;
else
ndays = ndays + 7 - remainingDays;
int inc = 1;
for (int i = 1; i <= ndays; i++) {
String day = sdf.format(cal.getTime());
System.out.println(day + "<<<");
Log.e("quest", day + "<<<");
inc++;
if (val == 0) {
firstweek = day.substring(0, 6);
// weeklist.add(firstweek);
val = 1;
}
if (i % 7 == 0) {
String s = day.substring(0, 6);
weeklist.add(firstweek + " to " + s);
val = 0;
Log.e("weekdayss", "=======week days===========" + weeklist);
inc = 0;
}
if (inc >= 1 && i == ndays) {
for (int ii = inc; ii <= 6; ii++) {
String dayi = sdf.format(cal.getTime());
System.out.println(dayi + "<<<");
Log.e("quest1", dayi + "<<<");
inc++;
}
}
cal.add(Calendar.DATE, 1);
}
if (weeklist.size() == 5) {
weeklist.remove(4);
}
if (weeklist.size() == 6) {
weeklist.remove(5);
weeklist.remove(4);
}
}
Problem
Want to get previous four weeks, not current Month four weeks
OUTPUT
[
02-Mar to 08-Mar
09-Mar to 15-Mar
16-Mar to 22-Mar
23-Mar to 29-Mar
]
A good alternative is to use the threeten backport - in Android here's how to configure it. Or, if you're using API level >= 26, just use the java.time classes.
This API makes things much easier. You can use the WeekFields class to define your week (starting on Friday):
// week starts on Friday
WeekFields wf = WeekFields.of(DayOfWeek.FRIDAY, 1);
The first parameter (DayOfWeek.FRIDAY) is the first day of the week, and the second parameter is the number of days in the first week. Check the documentation for more details about how these fields affect the class behaviour.
To get the current date, you can use the LocalDate class:
// current date
LocalDate dt = LocalDate.now();
Then you make a loop that subtracts a certain number of weeks, and use the WeekFields to get the first and last day of each week. I also used a DateTimeFormatter to print the dates to same format of your output:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MMM", Locale.ENGLISH);
// get previous 4 weeks
for (int i = 4; i >= 1; i--) {
LocalDate pastWeek = dt.minusWeeks(i);
LocalDate startOfWeek = pastWeek.with(wf.dayOfWeek(), 1);
LocalDate endOfWeek = pastWeek.with(wf.dayOfWeek(), 7);
// you can add this String to your weekList
String week = startOfWeek.format(fmt) + " to " + endOfWeek.format(fmt);
System.out.println(week);
}
Output:
23-Feb to 01-Mar
02-Mar to 08-Mar
09-Mar to 15-Mar
16-Mar to 22-Mar
How to Change start date and end date of month in calroid calendar lib if i want to modify calendar with shift my month start from 15 jan 2016 to 16 feb 2016.
Hello using following modification in CalendarHelper class you can set start date of month for shift calendar. I am using following library for calendar view https://github.com/roomorama/Caldroid
please modify getFullWeeks method
/**
* Retrieve all the dates for a given calendar month Include previous month,
* current month and next month.
*
* #param month
* #param year
* #param startDayOfWeek : calendar can start from customized date instead of Sunday
* #return
*/
public static ArrayList<DateTime> getFullWeeks(int month, int year, int startDayOfWeek,int startDayOfMonth, boolean sixWeeksInCalendar) {
ArrayList<DateTime> datetimeList = new ArrayList<DateTime>();
int dayCount=startDayOfMonth;
DateTime firstDateOfMonth = new DateTime(year, month, 1, 0, 0, 0, 0);
DateTime firstDateOfMonthToSet = new DateTime(year, month, dayCount, 0, 0, 0, 0);
int daysToAdd=firstDateOfMonth.getNumDaysInMonth()-dayCount;
DateTime lastDateOfMonth = firstDateOfMonthToSet.plusDays(daysToAdd);
DateTime lastDateOfMonthTpSet =firstDateOfMonthToSet.plusDays(firstDateOfMonth.getNumDaysInMonth()-1);
// Add dates of first week from previous month
// int weekdayOfFirstDate = firstDateOfMonth.getWeekDay();
//dr
int weekdayOfFirstDate = firstDateOfMonthToSet.getWeekDay();
// If weekdayOfFirstDate smaller than startDayOfWeek
// For e.g: weekdayFirstDate is Monday, startDayOfWeek is Tuesday
// increase the weekday of FirstDate because it's in the future
if (weekdayOfFirstDate < startDayOfWeek) {
weekdayOfFirstDate += 7;
}
while (weekdayOfFirstDate > 0) {
DateTime dateTime = firstDateOfMonthToSet.minusDays(weekdayOfFirstDate
- startDayOfWeek);
if (!dateTime.lt(firstDateOfMonthToSet)) {
break;
}
datetimeList.add(dateTime);
weekdayOfFirstDate--;
}
// Add dates of current month
for (int i = 0; i < lastDateOfMonth.getDay(); i++) {
datetimeList.add(firstDateOfMonthToSet.plusDays(i));
}
// Add dates of last week from next month
int endDayOfWeek = startDayOfWeek - 1;//dr
// int endDayOfWeek = startDayOfWeek;
if (endDayOfWeek == 0) {
endDayOfWeek = 7;
}
if (lastDateOfMonthTpSet.getWeekDay() != endDayOfWeek) {
int i = 1;
while (true) {
DateTime nextDay = lastDateOfMonthTpSet.plusDays(i);
datetimeList.add(nextDay);
i++;
if (nextDay.getWeekDay() == endDayOfWeek) {
break;
}
}
}
// Add more weeks to fill remaining rows
if (sixWeeksInCalendar) {
int size = datetimeList.size();
int row = size / 7;
int numOfDays = (6 - row) * 7;
DateTime lastDateTime = datetimeList.get(size - 1);
for (int i = 1; i <= numOfDays; i++) {
DateTime nextDateTime = lastDateTime.plusDays(i);
datetimeList.add(nextDateTime);
}
}
return datetimeList;
}
Hope this will help you :)
The following code sometimes give correct output And sometimes gives wrong
For example :
7th april 1990 returns Monday which is correct
31st dec 1987 returns Sunday which is incorrect, it should be Tuesday
I have tried:
int mm=Integer.parseInt(m);
GregorianCalendar calendar = new GregorianCalendar(Integer.parseInt(y),mm,Integer.parseInt(d));
int i = calendar.get(Calendar.DAY_OF_WEEK);
String dayOfTheWeek = null;
if(i == 2){
dayOfTheWeek = "Monday";
} else if (i==3){
dayOfTheWeek = "Tuesday";
} else if (i==4){
dayOfTheWeek = "Wednesday";
} else if (i==5){
dayOfTheWeek = "Thursday";
} else if (i==6){
dayOfTheWeek = "Friday";
} else if (i==7){
dayOfTheWeek = "Saturday";
} else if (i==1){
dayOfTheWeek = "Sunday";
}
Log.v("Event Week",Integer.toString(i));
return dayOfTheWeek;
GregorianCalendar calendar = new GregorianCalendar(1987, 11, 31);
System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
Gives output as Saturday
and
GregorianCalendar calendar = new GregorianCalendar(1990, 3, 7);
System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
Gives output as Thursday
Which matches what the calendar shows.
Note: The month field is 0-index based. So, January is 0, and December is 11.
PS: The actual output to the above code is an integer. So, you will need to check the values and figure out the DAY.
I managed to solve my problem
The following code gives
1.Day of week based on birthdate of the coming birthday
2.Also tested with leap year Feb 29, works perfect
int checkFutureLeapYear=0;
Calendar today=Calendar.getInstance();
Calendar BDay=Calendar.getInstance();
int CYear=today.get(Calendar.YEAR);
// checking whether entered date contains Feb 29 ,if yes check whether //current year is leap years so that it can handle 29
if (Integer.parseInt(m)==02 && (Integer.parseInt(d)==29)) {
// if leap year leave the date as it as , since it can handle 29
if ((CYear % 4 == 0 && CYear % 100 != 0) || (CYear % 400 == 0)) {
d=d;
}
// if not subtract 1 from date , to make it 28 , as current year donot contains feb 29 ,so making it feb 28
else {
int date=Integer.parseInt(d);
date=(date-1);
d=Integer.toString(date);
}
}
String startDate=y+"/"+m+"/"+d;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
Date date=null;
try{
date=sdf.parse(startDate);
}
catch (Exception e) {
e.printStackTrace();
}
BDay.setTime(date);
int BMonth=BDay.get(Calendar.MONTH);
int BDate=BDay.get(Calendar.DATE);
int CMonth=today.get(Calendar.MONTH);
int CDate=today.get(Calendar.DATE);
BDay.set(Calendar.YEAR,today.get(Calendar.YEAR));
// if current month is greater than birth month , then there is no birthday in the current year , means birthday has gone for the year.Hence looking for birthday in the next year by adding 1 to the current year
if (BMonth<CMonth) {
BDay.set(Calendar.YEAR,today.get(Calendar.YEAR)+1);
checkFutureLeapYear=1;
}
// Also if current month and birth month are same , but current date is greater than birth date , then there is no birthday in the current year , means birthday has gone for the year.Hence looking for birthday in the next year by adding 1 to the current year
else if ((BMonth==CMonth)&&(BDate<CDate)) {
BDay.set(Calendar.YEAR,today.get(Calendar.YEAR)+1);
checkFutureLeapYear=1;
}
// code to check that ,is the future year can handle feb 29, same as above conditions
if (checkFutureLeapYear==1) {
CYear=BDay.get(Calendar.YEAR);
Log.v("checkFutureLeapYear",Integer.toString(CYear));
; if (Integer.parseInt(m)==02 && (Integer.parseInt(d)==29)) {
if ((CYear % 4 == 0 && CYear % 100 != 0) || (CYear % 400 == 0)) {
d=d;
}
else {
int date1=Integer.parseInt(d);
date1=(date1-1);
d=Integer.toString(date1);
Log.v("Date 29 subtracted to ",(d));
}
}
startDate=Integer.toString(CYear)+"/"+m+"/"+d;
sdf=new SimpleDateFormat("yyyy/MM/dd");
date=null;
try{
date=sdf.parse(startDate);
}
catch (Exception e) {
e.printStackTrace();
}
BDay.setTime(date);
Log.v("dfdfgdffgfgb",Integer.toString(BDay.get(Calendar.YEAR)));
}
String dayOfTheWeek;
Log.v("Birth year",Integer.toString(BDay.get(Calendar.YEAR)));
Log.v("Birth month",Integer.toString(BDay.get(Calendar.MONTH)));
Log.v("Birth date",Integer.toString(BDay.get(Calendar.DAY_OF_MONTH)));
SimpleDateFormat mFormat = new SimpleDateFormat("EEEE", Locale.US);
dayOfTheWeek = mFormat.format(BDay.getTime());
return dayOfTheWeek;
I am creating a feature in an Android app to get an arbitrary date (past, present or future) and find the difference relative to now.
Both my now and due variables are longs, and this is my code:
long now = System.currentTimeMillis();
long due = now + 864000;
Log.d("Time in 1 day", DateUtils.getRelativeTimeSpanString(due,now, DateUtils.DAY_IN_MILLIS));
I want the output to be something like yesterday, today, in 4 days or 19/12/2012. However, the current output returns in 0 days...
I don't want the time to appear on these date strings.
What am I doing wrong and is the best method for formatting dates on Android?
What I have in mind is changing:
DateUtils.getRelativeTimeSpanString(due, now, 0L, DateUtils.FORMAT_ABBREV_ALL);
Since the documentation says it returns the time relative to now.
If that fails use some of the brilliant libraries:
Joda Time
PrettyTime
TimeAgo
Finally I have implemented what you wanted..!
First you need to download Joda Time from here
Extract it to any folder and put joda-time-2.2.jar into androidProject/libs folder.
MainActivity
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Months;
import org.joda.time.MutableDateTime;
import org.joda.time.Weeks;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
public class MainActivity extends Activity
{
private int day ;
private int month ;
private int year ;
private int hour ;
private int minute ;
private long selectedTimeInMillis;
private long currentTimeInMillis;
private String strDay ="";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
year = 2013;
month = 8;
day = 10;
hour = 15;
minute = 28;
DateTime selectedTime = new DateTime(year,month,day,hour,minute);
selectedTimeInMillis = selectedTime.getMillis();
MutableDateTime epoch = new MutableDateTime();
epoch.setDate(selectedTimeInMillis); //Set to Epoch time
DateTime now = new DateTime();
currentTimeInMillis = now.getMillis();
int days = Days.daysBetween(epoch, now).getDays();
int weeks = Weeks.weeksBetween(epoch, now).getWeeks();
int months = Months.monthsBetween(epoch, now).getMonths();
Log.v("days since epoch: ",""+days);
Log.v("weeks since epoch: ",""+weeks);
Log.v("months since epoch: ",""+months);
if(selectedTimeInMillis < currentTimeInMillis) //Past
{
long yesterdayTimeInMillis = currentTimeInMillis - 86400000;
DateTime today = new DateTime(currentTimeInMillis);
int year = today.getDayOfYear();
int intToday = today.getDayOfMonth();
DateTime yesterday = new DateTime(yesterdayTimeInMillis);
int intYesterday = yesterday.getDayOfMonth();
DateTime selectedDay = new DateTime(selectedTimeInMillis);
int intselectedDay = selectedDay.getDayOfMonth();
int intselectedYear = selectedDay.getDayOfYear();
if(intToday == intselectedDay & year == intselectedYear)
{
strDay = "today";
}
else if(intYesterday == intselectedDay)
{
strDay = "yesterday";
}
else
{
strDay = "before "+ days +" days from today";
}
}
else if(selectedTimeInMillis > currentTimeInMillis) //Future
{
long tomorrowTimeInMillis = currentTimeInMillis + 86400000;
DateTime tomorrow = new DateTime(tomorrowTimeInMillis);
int intTomorrow = tomorrow.getDayOfMonth();
DateTime today = new DateTime(selectedTimeInMillis);
int intToday = today.getDayOfMonth();
if(intToday == intTomorrow)
{
strDay = "tomorrow";
}
else
{
days = -days;
strDay = "after "+ days +" days from today";
}
}
Log.v("strDay: ",""+strDay);
}
}
You just need to change the value of day and you will get the desire output.
Currently I have given date 10 as input so output will be today.
I have set date/day = 10 , month = 8 , year = 2013 , hour = 15 , min = 28
For past dates:
input day 9 output yesterday
input day 3 output before 7 days from today
input year 2012 and day 10 output before 365 days from today
For future dates:
input day 11 output tomorrow
input day 27 output after 17 days from today
input day 23 and year 2016 output after 1109 days from today
Why not just check for yesterday and tomorrow to avoid the in 0 days/0 days ago bug and leave DateUtils.getRelativeTimeSpanString handle the remaining cases?
String relative = null;
if(now < due && (due-now)<864000){
relative = "tomorrow";
}else if(now > due && (now-due)<864000){
relative = "yesterday";
}else{
relative = DateUtils.getRelativeTimeSpanString(due, now, DateUtils.DAY_IN_MILLIS); // e.g. "in 4 days"
}
Log.d("result", relative);
Edit: You may also add today with a simple check as well.
Best way to format a date relative to now on Android
I suggest you to use JodaTime
It's lightweight handy library and i think actually the best tool for working with Date instances.
And you can start here.
build.gradle
compile 'joda-time:joda-time:2.9.9'
Utils.java
private static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MMM dd, yyyy");
private static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat(" 'at' h:mm aa");
public static String getRelativeDateTimeString(Calendar startDateCalendar) {
if (startDateCalendar == null) return null;
DateTime startDate = new DateTime(startDateCalendar.getTimeInMillis());
DateTime today = new DateTime();
int days = Days.daysBetween(today.withTimeAtStartOfDay(), startDate.withTimeAtStartOfDay()).getDays();
String date;
switch (days) {
case -1: date = "Yesterday"; break;
case 0: date = "Today"; break;
case 1: date = "Tomorrow"; break;
default: date = DATE_FORMAT.format(startDateCalendar.getTime()); break;
}
String time = TIME_FORMAT.format(startDateCalendar.getTime());
return date + time;
}
Output
Yesterday at 9:52 AM
Today at 9:52 AM
Tomorrow at 9:52 AM
Sep 05, 2017 at 9:52 AM
The actual reason is the number 864000 is in miliseconds, which corresponds to 14 minutes. 14 minutes is so small compared to DAY_IN_MILLIS (a day). There for you get "in 0 days".
If you want it to produce "in 14 mins", just change DAY_IN_MILLIS to MIN_IN_MILLIS.
I came here for an alternative but I can't find perfect rather than my code.
So I shared here any improvements are welcome.
public String getCreatedAtRelative() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
df.setTimeZone(TimeZone.getTimeZone("IST"));
CharSequence relative = null;
try {
relative = DateUtils.getRelativeTimeSpanString(df.parse(createdAt).getTime(), new Date().getTime(),
0L, DateUtils.FORMAT_ABBREV_ALL);
} catch (ParseException e) {
Log.e("Parse Exception adapter", "created at", e);
} catch (NullPointerException e) {
e.printStackTrace();
}
if (null == relative) {
return createdAt;
} else {
return relative.toString().replace(".", " ");
}
}
So your computation is based on milliseconds unit, then you format the result with SimpleDateFormat.
For this, you can easily use SimpleDateFormat formatter like this :
Date date = new Date(milliseconds);
SimpleDateFormat formatter = new SimpleDateFormat("EEEE dd MMMM yyyy");
String strDate = formatter.format(date);
So your computation should be based on milliseconds unit, then you format the result with SimpleDateFormat.
The pattern ("EEEE dd MMMM yyyy") allows you to get a date format like Monday, 04 February 2013.
You can change the pattern as you like : "EEEE dd/MM/yy", ...
for Android you can use most simple way with Joda-Time-Android library:
Date yourTime = new Date();
DateTime dateTime = new DateTime(yourTime); //or simple DateTime.now()
final String result = DateUtils.getRelativeTimeSpanString(getContext(), dateTime);
long now = System.currentTimeMillis();
DateUtils.getRelativeDateTimeString(mContext, now), DateUtils.SECOND_IN_MILLIS, DateUtils.DAY_IN_MILLIS, 0)
a link!