I got this problem cause my DatePicker not set text to textView on first try but after first try it can set without any problem.
This is my setDate Function, it will work after click at Linearlayout.
public void setBirthDate(){
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(calendar.MONTH);
int day = calendar.get(calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog( setting.this,
datePickerDialog,
year, month, day);
dialog.getWindow();
dialog.show();
datePickerDialog = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
month += 1;
String date = null;
if (month < 10) {
if (day < 10) {
date = "0" + day + "/" + "0" + month + "/" + year;
} else if (day >= 10) {
date = day + "/" + "0" + month + "/" + year;
}
} else if (month >= 10) {
if (day < 10) {
date = "0" + day + "/" + month + "/" + year;
} else if (day >= 10) {
date = day + "/" + month + "/" + year;
}
}
Toast.makeText(setting.this, date, Toast.LENGTH_SHORT).show();
textView_birthdate.setText(date);
}
};
}
And this is how I handle event.
#Override
public void onClick(View v){
if(v.getId() == R.id.settinglo_birthdate){
setBirthDate();
}
else if(){}
...
...
...
}
This is my onCreate
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_02);
list_linear = new ArrayList<>();
list_textview = new ArrayList<>();
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.settingtb);
toolbar.setCollapsible(true);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Setting");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
initialVIew();
}
This is initialView() method
public void initialVIew(){
/* layout initial & add to list */
list_linear.add(linear_fname = (LinearLayout) findViewById(R.id.settinglo_fname));
list_linear.add(linear_lname = (LinearLayout) findViewById(R.id.settinglo_lname));
list_linear.add(linear_birthdate = (LinearLayout) findViewById(R.id.settinglo_birthdate));
list_linear.add(linear_gender = (LinearLayout) findViewById(R.id.settinglo_gender));
list_linear.add(linear_tel = (LinearLayout) findViewById(R.id.settinglo_tel));
list_linear.add(linear_carefname = (LinearLayout) findViewById(R.id.settinglo_c_fname) );
list_linear.add(linear_carelname = (LinearLayout) findViewById(R.id.settinglo_c_lname) );
list_linear.add(linear_careemail = (LinearLayout) findViewById(R.id.settinglo_c_email) );
list_linear.add(linear_caretel = (LinearLayout) findViewById(R.id.settinglo_c_tel) );
list_linear.add(linear_min = (LinearLayout) findViewById(R.id.settinglo_glucose_min) );
list_linear.add(linear_max = (LinearLayout) findViewById(R.id.settinglo_glucose_max) );
/* textView initial & add to list */
list_textview.add(textView_fname = (TextView) findViewById(R.id.settingtv_fname));
list_textview.add(textView_lname = (TextView) findViewById(R.id.settingtv_lname));
list_textview.add(textView_birthdate = (TextView) findViewById(R.id.settingtv_birthdate));
list_textview.add(textView_gender = (TextView) findViewById(R.id.settingtv_gender));
list_textview.add(textView_tel = (TextView) findViewById(R.id.settingtv_tel));
list_textview.add(textView_carefname = (TextView) findViewById(R.id.settingtv_c_fname) );
list_textview.add(textView_carelname = (TextView) findViewById(R.id.settingtv_c_lname) );
list_textview.add(textView_careemail = (TextView) findViewById(R.id.settingtv_c_email) );
list_textview.add(textView_caretel = (TextView) findViewById(R.id.settingtv_c_tel) );
list_textview.add(textView_min = (TextView) findViewById(R.id.settingtv_glucose_min) );
list_textview.add(textView_max = (TextView) findViewById(R.id.settingtv_glucose_max) );
// layout set event
for(LinearLayout linearLayout : list_linear){
linearLayout.setOnClickListener(this);
}
// textView set event
for(TextView textView : list_textview){
textView.setOnClickListener(this);
}
}
Now I'm got confuse with this other onClick on other LinearLayout work fine without any problem. Only setDate that not first on first time.
You should modify the setBirthDate() like this below:-
You should initiate the new DatePickerDialog.OnDateSetListener() first before initialising new DatePickerDialog()
public void setBirthDate(){
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(calendar.MONTH);
int day = calendar.get(calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
month += 1;
String date = null;
if (month < 10) {
if (day < 10) {
date = "0" + day + "/" + "0" + month + "/" + year;
} else if (day >= 10) {
date = day + "/" + "0" + month + "/" + year;
}
} else if (month >= 10) {
if (day < 10) {
date = "0" + day + "/" + month + "/" + year;
} else if (day >= 10) {
date = day + "/" + month + "/" + year;
}
}
Toast.makeText(SimpleActivity.this, date, Toast.LENGTH_SHORT).show();
textView_birthdate.setText(date);
}
};
DatePickerDialog dialog = new DatePickerDialog( SimpleActivity.this,
datePickerDialog,
year, month, day);
dialog.getWindow();
dialog.show();
}
Related
I`m currently trying to obtain a CountDownTimer based on the time in milliseconds of a Calendar object. The startTimer function works, so does the timerSort function. The thing is that when the timer gets initialized with the timeLeft value, it never start from a value lower than 60 seconds. This eventually causes delays bigger than 10 seconds. any suggestions?
Thank you.
Code:
private void startTimer(String x){
counter = new CountDownTimer(timeLeft,1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeft = millisUntilFinished;
updateCountdownText();
}
#Override
public void onFinish() {
timerRunning = false;
int comp = Integer.parseInt(x);
Toast.makeText(getApplicationContext(), "Alarm received!", Toast.LENGTH_LONG).show();
cal[comp].add(Calendar.MINUTE,rec[comp]);
//Update txt file
int month = cal[comp].get(Calendar.MONTH)+1;
int day = cal[comp].get(Calendar.DAY_OF_MONTH);
String data = cal[comp].get(Calendar.HOUR_OF_DAY) + ","
+cal[comp].get(Calendar.MINUTE) + ","
+day+ "," + month + ","
+cal[comp].get(Calendar.YEAR) + "," + rec[comp] + ",";
try {
FileOutputStream stream = new FileOutputStream(file[comp], false);
try {
stream.write(data.getBytes());
}catch (Exception e){
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//end update
timerSort();
BluetoothGattCharacteristic C = btper.getCharacteristic(UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"),UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"));
//If device is disconnected => it will crash
btper.writeCharacteristic(C , x.getBytes(StandardCharsets.UTF_8), WriteType.WITH_RESPONSE);
speak(String.valueOf(comp+1));
}
}.start();
}
private void updateCountdownText() {
if(counterView.getVisibility() != View.VISIBLE)
counterView.setVisibility(View.VISIBLE);
int minutes = (int)timeLeft / 1000 / 60;
int seconds = (int)timeLeft /1000 % 60;
String timeLeftFormatted = String.format(Locale.getDefault(),"Time left until next pill: %02d:%02d",minutes,seconds);
if(timeLeftFormatted.contains("00:00"))
counterView.setVisibility(View.INVISIBLE);
counterView.setText(timeLeftFormatted);
}
private void resetTimer(){}
private void timerSort(){
Context context = getApplicationContext();
int i,j;
j = 0;
int fileindex = 0;
int hour, day, month, minute, year;
calendar = Calendar.getInstance();
timeLeft = 0;
for (i = 0; i<20; i++){
fileindex = i+1;
file[i] = new File(context.getExternalFilesDir(null).getAbsolutePath(),"pills"+fileindex+".txt");
cal[i] = (Calendar) calendar.clone();
//Read text from pills file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file[i]));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
String str = text.toString();
List<String> elephantList = Arrays.asList(str.split(","));
hour = Integer.parseInt(elephantList.get(0));
minute = Integer.parseInt(elephantList.get(1));
day = Integer.parseInt(elephantList.get(2));
month = Integer.parseInt(elephantList.get(3));
year = Integer.parseInt(elephantList.get(4));
rec[i] = Integer.parseInt(elephantList.get(5));
cal[i].set(Calendar.HOUR_OF_DAY, hour);
cal[i].set(Calendar.MINUTE, minute);
cal[i].set(Calendar.DAY_OF_MONTH, day);
cal[i].set(Calendar.MONTH-1, month);
cal[i].set(Calendar.YEAR,year);
}
// sorting:
int letsgo = 0;
Calendar tudor = Calendar.getInstance();
tudor.set(Calendar.YEAR,calendar.getMaximum(Calendar.YEAR));
for (i = 0; i<20; i++){
if(tudor.after(cal[i]) && cal[i].after(calendar)){
tudor = cal[i];
letsgo = i;
}
}
Toast.makeText(getApplicationContext(), String.valueOf(letsgo), Toast.LENGTH_LONG).show();
TextView nextPillView = (TextView) findViewById(R.id.nextPillView);
if (!cal[letsgo].after(calendar)) {
nextPillView.setText("No Pills Scheduled");
} else {
// timeLeft = cal[letsgo].getTimeInMillis() - calendar.getTimeInMillis() - Calendar.MILLISECOND;
int secleft = cal[letsgo].get(Calendar.SECOND)-calendar.get(Calendar.SECOND);
int minleft = cal[letsgo].get(Calendar.MINUTE)-calendar.get(Calendar.MINUTE);
timeLeft = secleft*1000 + minleft*60*1000 ;
//timeLeft = cal[letsgo].getTimeInMillis() - calendar.getTimeInMillis();
String theTime = String.format(Locale.getDefault(), "%02d:%02d", cal[letsgo].get(Calendar.HOUR_OF_DAY), cal[letsgo].get(Calendar.MINUTE));
month = cal[letsgo].get(Calendar.MONTH)+1;
nextPillView.setText(cal[letsgo].get(Calendar.HOUR_OF_DAY)+":"+cal[letsgo].get(Calendar.MINUTE)+ " | | Day: " + cal[letsgo].get(Calendar.DAY_OF_MONTH) + " | | Month: " + String.valueOf(month) + " | | Year: " + cal[letsgo].get(Calendar.YEAR));
startTimer(String.valueOf(letsgo));
}
}
private void speak(String x){
float pitch = 1;
float speed = 1;
mTTS.setPitch(pitch);
mTTS.setSpeechRate(speed);
mTTS.speak("It is time to administer the compartment with the lit LED",
TextToSpeech.QUEUE_ADD,null);
}
I am trying to get date doing calculations. For that I'm using Calendar cal = Calendar.getInstance();I am using this import import java.util.Calendar; When the app comes to onResume I am calling a method. In that method, the first line is getting Instance(). But for some reason, I am getting this error(ANR).
at java.util.Calendar.getInstance(Calendar.java:960)
at java.util.GregorianCalendar.<init>(GregorianCalendar.java:231)
at java.util.GregorianCalendar.<init>(GregorianCalendar.java:330)
at java.util.Calendar.<init>(Calendar.java:718)
at java.util.Calendar.<init>(Calendar.java:712)
Caused by: com.github.anrwatchdog.ANRError$$$_Thread: main
Caused by: com.github.anrwatchdog.ANRError: Application Not Responding
at com.github.anrwatchdog.ANRWatchDog.void run()(SourceFile:212)
at com.splunk.mint.Mint$3.void onAppNotResponding(com.github.anrwatchdog.ANRError)(SourceFile:297)
java.lang.Exception: com.github.anrwatchdog.ANRError: Application Not Responding
EDIT (adding code as asked)
public static int getCategory(final String time) {
long thenTime = SDKUtils.getLong(getLongValue(time));
Calendar c1 = Calendar.getInstance(); // today
Calendar c2 = Calendar.getInstance();
c2.setTime(new Date(thenTime)); // your date
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR))
return TODAY;
c1.add(Calendar.DAY_OF_YEAR, -1); // yesterday
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR))
return YESTERDAY;
c1 = Calendar.getInstance();
if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) )
return MONTH;
else
return YEAR;
}
public static String[] getSubTime(final String time, final int category) {
Calendar cal = Calendar.getInstance();
Date date = new Date(SDKUtils.getLong(getLongValue(time)));
TimeZone tz = TimeZone.getDefault();
cal.setTime(date);
cal.setTimeZone(tz);
int hour = cal.get(Calendar.HOUR_OF_DAY);
if (hour > 12)
hour = hour - 12;
int min = cal.get(Calendar.MINUTE);
String hourStr = hour < 10 ? "0" + hour : "" + hour;
String minStr = min < 10 ? "0" + min : "" + min;
String am = cal.get(Calendar.HOUR_OF_DAY) < 12 ? " AM" : " PM";
switch (category) {
case TODAY:
case YESTERDAY: {
return new String[] { hourStr + ":" + minStr + "", am };
}
case MONTH: {
int date_ = cal.get(Calendar.DAY_OF_MONTH);
String dateString = date_ < 10 ? "0" + date_ : date_ + "";
return new String[] { dateString, hourStr + ":" + minStr + "" + am };
}
case DATE: {
int date_ = cal.get(Calendar.DAY_OF_MONTH);
String dateString = date_ < 10 ? "0" + date_ : date_ + "";
return new String[] { dateString, hourStr + ":" + minStr + "" + am };
}
default: {
String month = convertNumberToMonthMMM(cal.get(Calendar.MONTH));
int date_ = cal.get(Calendar.DAY_OF_MONTH);
String dateString = date_ < 10 ? "0" + date_ : date_ + "";
return new String[] { month + " " + dateString, ", " + hourStr + ":" + minStr + "" + am };
}
}
}
These are the two methods i call. what is wrong?
Why you not try:
public class MainActivity extends AppCompatActivity
{
Calendar c = Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
}
}
Edit:
I think you're using:
import java.util.GregorianCalendar;
You try (add or) instead of:
import java.util.Calendar;
Regards
how to get first and last date of weeks on basis of month and year in android
ex:we pass month and year (March,2016) then i want all weeks just like
mar5- mar11,(sat to fri)
mar12- mar18,
mar19- mar25,
mar26-april01
please help me
Call this function to get results in a valid week pair list of given month of a year.
ex: getWeekStartEnd("December","2016");
Result: [
December3-December9,
December10-December16,
December17-December23,
December24-December30
]
List<String> getWeekStartEnd (String month , String year) {
List<String> validWeekPairs = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMMM-yyyy");
String day = "01";
try {
Date date = sdf.parse(day + "-" + month + "-" + year);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTime(date);
calendar.setFirstDayOfWeek(Calendar.SATURDAY);
List<String> startDayOfWeek = new ArrayList<>();
List<String> endDayOfWeek = new ArrayList<>();
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
boolean isStartDaySet = false;
boolean hasLastDayOfWeek = true;
for (int currentDay = 01; currentDay <= daysInMonth; currentDay++) {
Date newDate = sdf.parse(currentDay + "-" + month + "-" + year);
calendar.setTime(newDate);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SATURDAY) {
if (hasLastDayOfWeek) {
startDayOfWeek.add(month + String.valueOf(currentDay));
isStartDaySet = true;
hasLastDayOfWeek = false;
}
} else if (dayOfWeek == Calendar.FRIDAY) {
if (isStartDaySet) {
endDayOfWeek.add(month + String.valueOf(currentDay));
hasLastDayOfWeek = true;
}
}
}
for (int i = 0; i < endDayOfWeek.size(); i++) {
validWeekPairs.add(startDayOfWeek.get(i) + "-" + endDayOfWeek.get(i));
}
return validWeekPairs;
} catch (ParseException e) {
e.printStackTrace();
return validWeekPairs;
}catch (Exception e){
e.printStackTrace();
return validWeekPairs;
}
}
If you are using java.util.Date you can use the method getDay(). It returns Calendar constant, like Calendar.MONDAY.
You can pass the string as 02,2016
List<String> getWeekendsOftheMonth(String monthYearString) {
long monthDate;
List<String> weekEnds = new ArrayList<>();
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("dd,MM,yyyy");
try {
monthYearString="01,".concat(monthYearString);
monthDate = simpleDateFormat.parse(monthYearString).getTime();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(monthDate);
int maxDate = calendar.getActualMaximum(Calendar.DATE);
int minDate = calendar.getActualMinimum(Calendar.DATE);
for (int i = minDate; i <= maxDate; i++) {
calendar.set(Calendar.DATE, i);
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY|| calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
weekEnds.add(convertToDate(calendar.getTimeInMillis()));
}
}
}catch (Exception e){
e.printStackTrace();
}
return weekEnds;
}
String convertToDate(Long datetime) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM. yyyy");
Date date = new Date(datetime);
return simpleDateFormat.format(date);
}
you can do it from this method.
I have some code that I made to display a calendar using a GridView and I want to know if there is either an easier method of making a calendar, or if there is a way that I can change the appearance of a single item in the GridView for the current day. Code is below.
TextView tvMonth;
GridView gvCal;
DateFormat dateFormat;
Date date;
public static String[] days;
public static int[] months = {31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int today, beginOfMonth;
String month, year;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calender);
gvCal = (GridView) findViewById(R.id.gridView);
dateFormat = new SimpleDateFormat("yyyy");
date = new Date();
months[1] = Feb(Integer.parseInt(dateFormat.format(date))); // Find the amount of days in Feb
dateFormat = new SimpleDateFormat("MM");
int numDays = months[Integer.parseInt(dateFormat.format(date))-1] + 6; // Number of days in the month as well as making sure not to override the day names
// Check which day of the month the month started on. Eg: April 1st 2016 is a Friday
dateFormat = new SimpleDateFormat("MM");
month = dateFormat.format(date);
dateFormat = new SimpleDateFormat("yyyy");
year = dateFormat.format(date);
try {
beginOfMonth = (Day("01"+month+year))-1; // Get the beginning of the month (-1 because Android recognizes Sunday as the first day)
} catch (ParseException pe) {
Toast.makeText(getApplicationContext(), pe.getMessage(), Toast.LENGTH_LONG).show();
}
if (beginOfMonth == 0) {
beginOfMonth = 7;
}
days = new String[numDays+beginOfMonth];
days[0] = "Mon";
days[1] = "Tue";
days[2] = "Wed";
days[3] = "Thu";
days[4] = "Fri";
days[5] = "Sat";
days[6] = "Sun";
dateFormat = new SimpleDateFormat("dd");
String temp = dateFormat.format(date);
today = Integer.parseInt(temp);
if(beginOfMonth != 0) {
for (int i = 7; i <= (5 + beginOfMonth); i++) {
days[i] = "";
}
}
for (int i = (6 + beginOfMonth); i <= (days.length-1); i++) {
days[i] = Integer.toString(i-beginOfMonth-5);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.cal_days, days);
gvCal.setAdapter(adapter);
gvCal.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
tvMonth = (TextView) findViewById(R.id.textView);
dateFormat = new SimpleDateFormat("MMMM"); // Get month name
tvMonth.setText(dateFormat.format(date));
}
public int Feb(int year) {
int temp;
try {
temp = year / 4;
} catch (Exception e) {
return 28;
}
return 29;
}
public int Day(String day) throws ParseException {
DateFormat df = new SimpleDateFormat("ddMMyyyy");
try {
Date d = df.parse(String.valueOf(day));
Calendar c = Calendar.getInstance();
c.setTime(d);
return c.get(Calendar.DAY_OF_WEEK);
} catch (Exception e) {
ParseException pe = new ParseException("There was a problem getting the date.", 0);
throw pe;
}
}
"I want to know if there is either and easier method of making a calendar, or if there is a way that I can change the appearance of a single item in the GridView for the current day."
Check this library: https://github.com/SundeepK/CompactCalendarView
You can add events to a date that will be shown as a tiny cycle under the number of day.
I want to change the format of, Currently Date(YYYY-MM-DD) and Time (SS:MM:HH) to 'n' Months ago,'n' Days ago , 'n' Hours "ago" format.
CURRENT FORMAT:
REQUIRED FORMAT:
I am using Bean and Adapter class to get Current Date. Code is given Below;
Adapter Class:
public class MessageAdapter extends BaseAdapter {
private Activity activity;
private List<MessageBean> messageBeanList;
public ImageLoader imageLoader;
private Context context;
public MessageAdapter (Activity activity,List<MessageBean> messageBeanList)
{
super();
this.activity = activity;
// this.context = context;
this.messageBeanList = messageBeanList;
this.context=context;
}
#Override
public int getCount() {
return messageBeanList.size();
}
#Override
public Object getItem(int position) {
return messageBeanList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ItemHolder itemHolder = new ItemHolder();
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) activity.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(
R.layout.message_item, null);
imageLoader=new ImageLoader(activity.getApplicationContext());
itemHolder.timestampp = (TextView) convertView
.findViewById(R.id.timestamp);
convertView.setTag(itemHolder);
} else {
itemHolder = (ItemHolder) convertView.getTag();
}
class ItemHolder
{
public TextView timestampp;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
// Your code to nofify
}
}
BEAN CLASS:
import com.google.gson.annotations.SerializedName;
public class MessageBean {
#SerializedName("date_created")
private String dateCreated = "";
}
public String getDateCreated() {
return dateCreated;
}
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
Gone through almost every related question in SOF, but didn't get what I want as I am using bean and adapter class. Is this possible to convert Date and Time format if using JSON parsing?
I hope this will work for you..
Just add code in your adapter
/***************get current date time function*************/
String curDateTime = "";
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
String curDateTime = df.format(c.getTime());
}catch(Exception e){}
/***************get current date time function*************/
// add simple_date_format for uniqueness
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = simpleDateFormat.parse(messageBean.getDateCreated()); // like 2016-03-09 07:08:27
Date date2 = simpleDateFormat.parse(curDateTime); // 2016-03-09 07:08:27
differentDateTime = printDifference(date1, date2);
} catch (Exception e) {
e.printStackTrace();
}
itemHolder.timestampp.setText(differentDateTime);
/************function of print different for showing date into ago format***************/
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public String printDifference(Date startDate, Date endDate){
String allDaysMonsSeconds="";
//milliseconds
long different = endDate.getTime() - startDate.getTime();
Log.d("TAG","startDate : " + startDate);
Log.d("TAG","endDate : "+ endDate);
Log.d("TAG","different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long yearInMilli = daysInMilli * 365;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
long elapsedYears = different / yearInMilli;
Log.d("TAG","%d days, %d hours, %d minutes, %d seconds %n, %d years:"+elapsedDays+","+elapsedHours+","+elapsedMinutes+","+elapsedSeconds+","+elapsedYears);
// code for showing before days...
if(elapsedDays<=0){
if (elapsedHours<=0)
{
if (elapsedMinutes<=0)
{
allDaysMonsSeconds = elapsedSeconds+" second ago";
}
else
{
allDaysMonsSeconds = elapsedMinutes+" minute ago";
}
}
else
{
allDaysMonsSeconds = elapsedHours+" hour ago";
}
}
else{
allDaysMonsSeconds = elapsedDays+" day ago";
}
return allDaysMonsSeconds;
}
/************function of print different for showing date into ago format***************/
try this,
initialize your textview first.
TextView t = new TextView();
Call below method as,
getTimeDifference(date, t);
private void getTimeDifference(String pDate, TextView time) {
int diffInDays = 0;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar c = Calendar.getInstance();
String formattedDate = format.format(c.getTime());
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(formattedDate);
d2 = format.parse(pDate);
long diff = d1.getTime() - d2.getTime();
diffInDays = (int) (diff / (1000 * 60 * 60 * 24));
if (diffInDays > 0) {
if (diffInDays == 1) {
time.setText(diffInDays + " day ago");
} else {
time.setText(diffInDays + " days ago");
}
} else {
int diffHours = (int) (diff / (60 * 60 * 1000));
if (diffHours > 0) {
if (diffHours == 1) {
time.setText(diffHours + " hr ago");
} else {
time.setText(diffHours + " hrs ago");
}
} else {
int diffMinutes = (int) ((diff / (60 * 1000) % 60));
if (diffMinutes == 1) {
time.setText(diffMinutes + " min ago");
} else {
time.setText(diffMinutes + " mins ago");
}
}
}
} catch (ParseException e) {
// System.out.println("Err: " + e);
e.printStackTrace();
}
}
Use the following code and just concatenate ago as a string in the time:
startTime = "2016-03-09 16:23:30";
StringTokenizer tk = new StringTokenizer(startTime);
String date = tk.nextToken();
String time = tk.nextToken();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
SimpleDateFormat sdfs = new SimpleDateFormat("hh:mm a");
Date dt;
try {
dt = sdf.parse(time);
System.out.println("Time Display: " + sdfs.format(dt)+" ago"); // <-- I got result here
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String curDateTime = "";
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
String curDateTime = df.format(c.getTime());
}catch(Exception e){}
/***************get current date time function*************/
// add simple_date_format for uniqueness
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = simpleDateFormat.parse(messageBean.getDateCreated()); // like 2016-03-09 07:08:27
Date date2 = simpleDateFormat.parse(curDateTime); // 2016-03-09 07:08:27
differentDateTime = printDifference(date1, date2);
} catch (Exception e) {
e.printStackTrace();
}
itemHolder.timestampp.setText(differentDateTime);
/************function of print different for showing date into ago format***************/
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public String printDifference(Date startDate, Date endDate){
String allDaysMonsSeconds="";
//milliseconds
long different = endDate.getTime() - startDate.getTime();
Log.d("TAG","startDate : " + startDate);
Log.d("TAG","endDate : "+ endDate);
Log.d("TAG","different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long yearInMilli = daysInMilli * 365;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
long elapsedYears = different / yearInMilli;
Log.d("TAG","%d days, %d hours, %d minutes, %d seconds %n, %d years:"+elapsedDays+","+elapsedHours+","+elapsedMinutes+","+elapsedSeconds+","+elapsedYears);
// code for showing before days...
if(elapsedDays<=0){
if (elapsedHours<=0)
{
if (elapsedMinutes<=0)
{
allDaysMonsSeconds = elapsedSeconds+" second ago";
}
else
{
allDaysMonsSeconds = elapsedMinutes+" minute ago";
}
}
else
{
allDaysMonsSeconds = elapsedHours+" hour ago";
}
}
else{
allDaysMonsSeconds = elapsedDays+" day ago";
}
return allDaysMonsSeconds;
}