2013-02-04 9 views
31

Sto creando una funzionalità in un'app Android per ottenere una data arbitraria (passata, presente o futura) e trovare la differenza relativa ad ora.Il modo migliore per formattare una data relativa ad ora su Android

Entrambi i miei now e due variabili sono longs, e questo è il mio codice:

long now = System.currentTimeMillis(); 
long due = now + 864000; 

Log.d("Time in 1 day", DateUtils.getRelativeTimeSpanString(due,now, DateUtils.DAY_IN_MILLIS)); 

voglio l'uscita di essere qualcosa di simile yesterday, today, in 4 days o 19/12/2012. Tuttavia, l'output corrente restituisce in 0 days ...

I non desidera che venga visualizzata l'ora in queste stringhe di data.

Cosa sto facendo male ed è il metodo migliore per la formattazione delle date su Android?

risposta

-1

Quindi il calcolo si basa su un'unità millisecondi, quindi il risultato viene formattato con SimpleDateFormat.

Per questo, si può facilmente usare SimpleDateFormat formattatore come questo:

Date date = new Date(milliseconds); 
SimpleDateFormat formatter = new SimpleDateFormat("EEEE dd MMMM yyyy"); 
String strDate = formatter.format(date); 

Così il vostro calcolo dovrebbe essere basata su unità di millisecondi, quindi si formatta il risultato con SimpleDateFormat.

Il modello ("EEEE dd MMMM yyyy") consente di ottenere un formato di data come Lunedi, 04 febbraio 2013.

È possibile modificare il modello di come ti piace: "EEEE gg/mm/aa", ...

+0

Che non mi darà * date relative * se lo farà ? Voglio date come 'today' e' in due giorni ' –

2

modo migliore per formattare una data relativa ad ora su Android

io suggerisco di utilizzare JodaTime

E 'lightwe ight a portata di mano e penso che sia lo strumento migliore per lavorare con le istanze di Date.

E è possibile avviare here.

+6

Una libreria da 500kb per qualcosa di semplice come questo? A meno che la mia app non sia realmente dipendente dalle date (ad es.un'app di calendario), mi limiterei a usare 'DateUtils', che è incorporato nel sistema operativo. –

+0

@WordPressDeveloper JodaTime è in realtà il migliore, ma io rispetto la tua opinione. – Sajmon

+0

Sono d'accordo con @ hasMobi-AndroidApps Non esiste una libreria "migliore". Si tratta di compromessi. – JakeWilson801

25

Quello che ho in mente sta cambiando:

DateUtils.getRelativeTimeSpanString(due, now, 0L, DateUtils.FORMAT_ABBREV_ALL);

Dal momento che la documentazione dice che restituisce il tempo relativo ad ora.

Se fallisce utilizzare alcune delle librerie brillanti:

Joda Time

PrettyTime

TimeAgo

+0

Questo non funzionerà se ho bisogno di diff in giorni! Per es. "14 giorni fa" non "2 settimane fa" – oleynikd

+0

@oleynikd usa DateUtils.DAY_IN_MILLIS invece di 0L – joao2fast4u

4

Perché non basta controllare per yesterday e tomorrow per evitare il bug in 0 days/0 days ago e lasciare DateUtils.getRelativeTimeSpanString gestire i casi rimanenti?

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: Si può anche aggiungere today con un semplice controllo pure.

+0

Questo non sembra funzionare bene se il tempo è più di qualche settimana fa. La funzione restituisce invece il mese e la data (ad esempio, 2 febbraio). –

8

Infine ho implementato quello che volevi ..!

Prima di tutto bisogna scaricare Joda Time from here

estrarlo in una cartella qualsiasi e mettere Joda-tempo-2.2.jar nella cartella/libs androidProject.

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); 
    } 
} 

Hai solo bisogno di cambiare il valore di giorno e si otterrà l'output desiderio. Attualmente ho dato la data 10 come input così l'output sarà oggi.

ho impostato data/giorno = 10, mese = 8, anno = 2013, ora = 15, min = 28

Per date passate:

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 

Per le date future:

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 
+4

Prettytime lib è anche formato di tempo leggibile molto umano http://www.londatiga.net/it/programming/android/how-to-convert-time-in-millisecond-into-relative-time-format-in-android/ –

+0

@Lorensius WL T Grazie. Lo testerò. – TheFlash

+0

oh stavo cercando questo, ora ho provato questo approccio e lavorando come un personaggio di fascino! Grazie uomo –

0

per Android è possibile utilizzare modo più semplice, con Joda-Time-Android libreria:

Date yourTime = new Date(); 
DateTime dateTime = new DateTime(yourTime); //or simple DateTime.now() 
final String result = DateUtils.getRelativeTimeSpanString(getContext(), dateTime); 
+0

Esempio da TinTran? – ultraon

0

Il motivo reale è il numero 864000 è in millisecondi, che corrisponde a 14 minuti. 14 minuti sono così piccoli rispetto a DAY_IN_MILLIS (al giorno). Lì per te arriva "in 0 giorni". Se vuoi produrre "in 14 minuti", cambia DAY_IN_MILLIS a MIN_IN_MILLIS.

+0

Voglio ottenere "oggi"! Non "in 0 giorni" o "in 14 minuti" – oleynikd

-2

long now = System.currentTimeMillis();

DateUtils.getRelativeDateTimeString (mContext, ora), DateUtils.SECOND_IN_MILLIS, DateUtils.DAY_IN_MILLIS, 0)

a link!

0

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; 
    } 

uscita

Yesterday at 9:52 AM 
Today at 9:52 AM 
Tomorrow at 9:52 AM 
Sep 05, 2017 at 9:52 AM 
Problemi correlati