Comparing two times in android - android

I have tried with the below code to compare two times:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
Date inTime = sdf.parse("11:00");
Date outTime = sdf.parse("10:00");
if(inTime.compareTo(outTime) > 0){
Toast.makeText(this, "Out time should be greater than In time", Toast.LENGTH_SHORT).show();
}
Above code is working fine.
But if I give in time as 11:00 and out time as 12:00, I am getting above toast message.
I am getting above toast message if I give out time from 12:00 to 12:59. In other cases above code is working fine.
Where I am doing wrong. Please help me.

Change SimpleDateFormat like below...
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Below are the patterns:
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
This will work....

tl;dr
Use java.time.
LocalTime
.parse( "12:00" )
.isAfter(
LocalTime.parse( "11:00" )
)
java.time
You have three problems:
You are using terrible old date-time classes (Date & SimpleDateFormat) that were supplanted years ago by the modern java.time classes.
Your format of hh:mm should have been uppercase for 24-hour clock rather than 12-hour clock: HH:mm.
You are inappropriately trying to represent a time-of-day with a class meant for date-with-time-of-day values.
Use LocalTime. This class represents a time-of-day without a date and without a time zone.
LocalTime start = LocalTime.parse( "11:00" ) ;
LocalTime stop = LocalTime.parse( "12:00" ) ;
You can compare.
boolean isStopAfterStart = stop.isAfter( start ) ;
Calculate the elapsed time as a Duration.
Duration d = Duration.between( start , stop ) ;
d.toString(): PT1H
You can also ask the Duration if it is negative, as another way to detect the stop time being before the start.
boolean isStopBeforeStart = d.isNegative() ;
Caveat: Working on time-of-day without the context of a date and a time zone can produce unrealistic results. That approach ignores the anomalies that occur in time zones such as Daylight Saving Time (DST) and other shifts to the wall-clock time used by the people of a particular region. An hour can repeat, or be skipped. A day can be 23, 23.5, 23.75, 25, or other number of hours long.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by Ketan Ramani on 20/9/18.
*/
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
private static EditText text;
private static TextView textTv;
private static Date startDate = null;
private static Date fromTime = null;
public static TimePickerFragment getInstance(View view) {
if (view instanceof EditText) {
text = (EditText) view;
} else if (view instanceof TextView) {
textTv = (TextView) view;
}
return new TimePickerFragment();
}
public static TimePickerFragment getInstance(View view, Date fromTimeCalendar) {
if (view instanceof EditText) {
text = (EditText) view;
} else if (view instanceof TextView) {
textTv = (TextView) view;
}
fromTime = fromTimeCalendar;
return new TimePickerFragment();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute, true/*DateFormat.is24HourFormat(getActivity())*/);
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (fromTime != null) {
Calendar fromTimeCal = Calendar.getInstance();
fromTimeCal.setTime(fromTime);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
Date toDate = null;
try {
toDate = sdf.parse(String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute));
} catch (ParseException e) {
e.printStackTrace();
}
Calendar toTimeCal = Calendar.getInstance();
toTimeCal.setTime(toDate);
if (toTimeCal.getTimeInMillis()<fromTimeCal.getTimeInMillis()){
Helper.showToast(getActivity(),"To time can't less than from time");
} else {
if (text != null) {
text.setText(getFormatedTime(hourOfDay, minute));
} else if (textTv != null) {
textTv.setText(getFormatedTime(hourOfDay, minute));
}
}
} else {
if (text != null) {
text.setText(getFormatedTime(hourOfDay, minute));
} else if (textTv != null) {
textTv.setText(getFormatedTime(hourOfDay, minute));
}
}
}
private String getFormatedTime(int hourOfDay, int minute) {
int hour, min;
Calendar datetime = Calendar.getInstance();
String am_pm = "";
datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
datetime.set(Calendar.MINUTE, minute);
if (datetime.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (datetime.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
hourOfDay = hourOfDay > 12 ? hourOfDay - 12 : hourOfDay;
hour = hourOfDay > 9 ? hourOfDay : hourOfDay;
min = minute > 9 ? minute : minute;
return String.format("%02d", hour) + ":" + String.format("%02d", min) + " " + am_pm;
}
public void showTimePickerDialog(Context context, View view) {
DialogFragment newFragment = TimePickerFragment.getInstance(view);
newFragment.show(((AppCompatActivity) context).getSupportFragmentManager(), "TimePicker");
}
public void showTimePickerDialog(Context context, View view, Date fromTime) {
DialogFragment newFragment = TimePickerFragment.getInstance(view, fromTime);
newFragment.show(((AppCompatActivity) context).getSupportFragmentManager(), "TimePicker");
}
}
Use
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.et_from_time:
TimePickerFragment fromTime = new TimePickerFragment();
fromTime.showTimePickerDialog(context, v, null);
mToTimeEt.setText("Select To Time");
break;
case R.id.et_to_time:
if(mFromTimeEt.getText().toString().equalsIgnoreCase("Select From Time")){
Helper.showToast(context,"Please, select from time first");
} else {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
Date fromDate = null;
try {
fromDate = sdf.parse(mFromTimeEt.getText().toString());
} catch (ParseException e) {
e.printStackTrace();
}
TimePickerFragment toTime = new TimePickerFragment();
toTime.showTimePickerDialog(context, v, fromDate);
}
break;
}
}
This class will work for EditText and TextView and set time to respected EditText or TextView if To time is After From Time in HH:mm a Format

If you are using 24 hour time format then use kk instead of HH.
SimpleDateFormat sdf = new SimpleDateFormat("kk:mm");

Related

How to check if the date is today or not

I am getting the current date like below:
public void getCurrentDate(View view) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("yyyy / MM / dd ");
String strDate = "Current Date : " + mdformat.format(calendar.getTime());
display(strDate);
}
private void display(String num) {
TextView textView = (TextView) findViewById(R.id.current_date_view);
textView.setText(num);
}
But I want to check whether the date is today's date or not. But I am not getting how to check that.
You can do as #aliaksei's answer, which works fine. But in Android you can also use java.time (API level 26) or ThreetenABP if java.time is not available.
But first you must consider the fact that "today's date" is relative. Now, at this very moment, each part of the world might be in a different "today". In America and Europe it's April 10th, but in some parts of the Pacific it's already April 11th.
You can choose a specific timezone, or just use the device's zone, which I think it's the case. In this case, just use the JVM default timezone.
Then you use the ThreetenABP to convert the Calendar to a LocalDate and then compare with today's date:
// calendar I want to check
Calendar cal = ...
// convert to LocalDate
LocalDate date = DateTimeUtils.toZonedDateTime(cal).toLocalDate();
// compare with today (now() is using the JVM default timezone)
if (date.isEqual(LocalDate.now(ZoneId.systemDefault()))) {
// today
}
public static boolean isSameDay(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("The dates must not be null");
}
return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
}
Or you could use the DateUtils class that this snippet is from :)

Android date parsing (Extracting month and year )

I want my app to parse the date in format "dd-MMM-yyyy". The date has been successfully parsed when I try to get month and get year it is giving other result. I inpued 06-sep-2014 as date. But when I try to extract month and year from the parsed date it is showing 8 for month instead of 9 and 114 for year instead of 2014.
logcat output
6
8
114
Here's my code
String date1 = "06 sep 2014";
SimpleDateFormat format1 = new SimpleDateFormat("dd MMM yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("d MMM yyyy");
Date date;
try {
if (date1.length() == 11) {
date = format1.parse(date1);
} else {
date = format2.parse(date1);
}
int day=date.getDate();
int mon1=date.getMonth();
int year1=date.getYear();
System.out.println("date is:"+ date);
System.out.println(day);
System.out.println(mon1);
System.out.println(year1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public final class DateParseDemo {
public static void main(String[] args){
final DateFormat df = new SimpleDateFormat("dd MMM yyyy");
final Calendar c = Calendar.getInstance();
try {
c.setTime(df.parse("06 sep 2014"));
System.out.println("Year = " + c.get(Calendar.YEAR));
System.out.println("Month = " + (c.get(Calendar.MONTH)));
System.out.println("Day = " + c.get(Calendar.DAY_OF_MONTH));
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
Output:
Year = 2014
Month = 8
Day = 6
And as for the month field, this is 0-based. This means that January = 0 and December = 11. As stated by the javadoc,
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
Because date.getyear Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
Maybe, You can use for example;
int year1=date.getYear();
System.out.println(year1+1900);
Using the Date class, it gives you the year starting from 1900. A better way to get what you want is using the Calendar class. See http://developer.android.com/reference/java/util/Date.html#getYear()

Have TextView show day of week as letters not integer

I have a textview which shows the day of the week as an integer (0-7). I would prefer if it could convert that to a string, which could then be shown in a TextView. My code is below. Also, how can I make it so the TextViews update the time, date, etc. (it only shows the time the app is opened)? Thanks in advance.
MainActivity.java:
package press.linx.calendar;
import java.sql.Date;
import java.text.SimpleDateFormat;
import android.os.Bundle;
import android.app.Activity;
import android.text.format.Time;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView day = (TextView)findViewById(R.id.day);
TextView month = (TextView)findViewById(R.id.month);
TextView year = (TextView)findViewById(R.id.year);
TextView time = (TextView)findViewById(R.id.time);
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
day.setText("" + today.monthDay); // Day of the month (0-31)
month.setText("" + today.month); // Month (0-11)
year.setText("" + today.year); // Year
time.setText("" + today.format("%k:%M")); // Current time
}
}
UPDATE: I got it using this piece of code:
final Calendar calendar = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("MMM"); // 3-letter month name & 2-char day of month
TextView datetxt = (TextView) findViewById(R.id.nameofyourtextview);
datetxt.setText(formatter.format(calendar.getTime()));
To format your Time:
Time time = new Time();
time.format("%A");
It returns name of day in week (Sunday, Friday..) - see description of format string (It's a PHP man page, but the symbols are same and it's well-aranged)
In order to make textViews updated every second you have to use Timer and TimerTask.
Define UpdateTimeTask:
class UpdateTimeTask extends TimerTask {
public void run() {
// Update time, must be called using runOnUiThread
}
}
and then set timer:
Timer timer = new Timer();
TimerTask updateTime = new UpdateTimeTask();
timer.scheduleAtFixedRate(updateTime, 0, 1000);
I assume you are looking for the date to be displayed in the below format.
You can use the below
Date now = new Date();
SimpleDateFormat dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy");
System.out.println("Format : " + dateFormatter.format(now));
Output
Format : Thursday, April 25, 2013
Few helpful links
http://www.ntu.edu.sg/home/ehchua/programming/java/DateTimeCalendar.html
http://www.roseindia.net/tutorial/java/core/convertDateToWords.html
To get the current day of the week (i.e. Monday, Tuesday, Wednesday, etc.) try:
DateFormat fmt = new SimpleDateFormat( "EEEE" );
fmt.format( new java.util.Date() );
Try this
month.setText(getMonth(today.month));
day.setText(getWeek(today.monthDay));
method to get month based on month number
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month];
}
method to get week based on week number
public String getWeek(int weekno) {
return new DateFormatSymbols().getWeekdays()[weekno];
}
Do you mean display as Mon, Tue, Wed,.... ?
Use this format.
SimpleDateFormat curFormatDate = new SimpleDateFormat("EEE");

Best way to format a date relative to now on Android

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!

Right way to format date with strings like today, yesterday, tomorrow etc

I have a date textview. And my textview holds a date string like 2011.09.17. Well I still do want to have that but I also want to add some more user friendly info for some specific dates like today or yesterday. For example if today is 2011.09.17 I want my textview to have value of yesterday instead 2011.09.16 and today instead 2011.09.17.
well I already managed to do this :), but in the ugly way :(. I do this with a lot of 'if->than' which is really uglly and what ever I want to add some new rule like if the date is older than one year I want to put string like last year or so.... I really need to add ugly logic.
My question is is there a nicer way to do this ? is there something like design pattern for this ? What is the recommended way to do this ? I am sure that many people have encounter this kind of problems
if there some bather approach than thousand of ifs ? if not thanks any way at least I will stop searching for bather solution
any suggestions , snippet or so will be appreciated
Thanks
You could try getRelativeDateTimeString in DateUtils
http://developer.android.com/reference/android/text/format/DateUtils.html
public class RelativeWeekday {
private final Calendar mCalendar;
public RelativeWeekday(Calendar calendar) {
mCalendar = calendar;
}
#Override
public String toString() {
Calendar today = Calendar.getInstance(Locale.getDefault());
int dayOfYear = mCalendar.get(Calendar.DAY_OF_YEAR);
if (Math.abs(dayOfYear - today.get(Calendar.DAY_OF_YEAR)) < 2) {
return getRelativeDay(today);
}
return getWeekDay();
}
private String getRelativeDay(Calendar today) {
return DateUtils.getRelativeTimeSpanString(
mCalendar.getTimeInMillis(),
today.getTimeInMillis(),
DateUtils.DAY_IN_MILLIS,
DateUtils.FORMAT_SHOW_WEEKDAY).toString();
}
private String getWeekDay() {
SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE");
return dayFormat.format(mCalendar.getTimeInMillis());
}
}
I usually use this handy java library for Relative Time formatting. Prety Time Library
Try this, i implemented it using joda-datatime2.2.jar and java SimpleDateFormat
import java.text.SimpleDateFormat;
import java.util.Date;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.Days;
public class SmartDateTimeUtil {
private static String getHourMinuteString(Date date){
SimpleDateFormat hourMinuteFormat = new SimpleDateFormat(" h:m a");
return hourMinuteFormat.format(date);
}
private static String getDateString(Date date){
SimpleDateFormat dateStringFormat = new SimpleDateFormat("EEE',' MMM d y',' h:m a");
return dateStringFormat.format(date);
}
private static boolean isToday (DateTime dateTime) {
DateMidnight today = new DateMidnight();
return today.equals(dateTime.toDateMidnight());
}
private static boolean isYesterday (DateTime dateTime) {
DateMidnight yesterday = (new DateMidnight()).minusDays(1);
return yesterday.equals(dateTime.toDateMidnight());
}
private static boolean isTomorrow(DateTime dateTime){
DateMidnight tomorrow = (new DateMidnight()).plusDays(1);
return tomorrow.equals(dateTime.toDateMidnight());
}
private static String getDayString(Date date) {
SimpleDateFormat weekdayFormat = new SimpleDateFormat("EEE',' h:m a");
String s;
if (isToday(new DateTime(date)))
s = "Today";
else if (isYesterday(new DateTime(date)))
s = "Yesterday," + getHourMinuteString(date);
else if(isTomorrow(new DateTime(date)))
s = "Tomorrow," +getHourMinuteString(date);
else
s = weekdayFormat.format(date);
return s;
}
public static String getDateString_shortAndSmart(Date date) {
String s;
DateTime nowDT = new DateTime();
DateTime dateDT = new DateTime(date);
int days = Days.daysBetween(dateDT, nowDT).getDays();
if (isToday(new DateTime(date)))
s = "Today,"+getHourMinuteString(date);
else if (days < 7)
s = getDayString(date);
else
s = getDateString(date);
return s;
}
}
Simple cases to use and test the Util class:
import java.util.Calendar;
import java.util.Date;
public class SmartDateTimeUtilTest {
public static void main(String[] args) {
System.out.println("Date now:"+SmartDateTimeUtil.getDateString_shortAndSmart(new Date()));
System.out.println("Date 5 days before :"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureDay(-5)));
System.out.println("Date 1 day before :"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureDay(-1)));
System.out.println("Date last month:"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureMonth(-1)));
System.out.println("Date last year:"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureDate(-1)));
System.out.println("Date 1 day after :"+SmartDateTimeUtil.getDateString_shortAndSmart(getFutureDay(1)));
}
public static Date getFutureDate(int numberOfYears){
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.YEAR, numberOfYears);
return c.getTime();
}
public static Date getFutureMonth(int numberOfYears){
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.MONTH, numberOfYears);
return c.getTime();
}
public static Date getFutureDay(int numberOfYears){
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, numberOfYears);
return c.getTime();
}
}
getRelativeTimeSpanString
added in API level 3
getRelativeTimeSpanString (long time,
long now,
long minResolution)
Returns a string describing 'time' as a time relative to 'now'.
Time spans in the past are formatted like "42 minutes ago". Time spans in the future are formatted like "In 42 minutes".
More information you can find here:
https://developer.android.com/reference/android/text/format/DateUtils
Calendar now = Calendar.getInstance();
return DateUtils.getRelativeTimeSpanString(time, now.getTimeInMillis(), DateUtils.DAY_IN_MILLIS);
For android Use JodaTime library in build.gradle file:
compile 'net.danlew:android.joda:2.9.9'
public static String formateddate(String date) {
DateTime dateTime = DateTimeFormat.forPattern("dd-MMM-yyyy").parseDateTime(date);
DateTime today = new DateTime();
DateTime yesterday = today.minusDays(1);
DateTime twodaysago = today.minusDays(2);
DateTime tomorrow= today.minusDays(-1);
if (dateTime.toLocalDate().equals(today.toLocalDate())) {
return "Today ";
} else if (dateTime.toLocalDate().equals(yesterday.toLocalDate())) {
return "Yesterday ";
} else if (dateTime.toLocalDate().equals(twodaysago.toLocalDate())) {
return "2 days ago ";
} else if (dateTime.toLocalDate().equals(tomorrow.toLocalDate())) {
return "Tomorrow ";
} else {
return date;
}
}

Categories

Resources