Last active
July 7, 2016 15:44
-
-
Save AlbertoMonteiro/5401330 to your computer and use it in GitHub Desktop.
Relative datetime in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Locale; | |
import org.joda.time.DateTime; | |
import org.joda.time.Period; | |
import org.joda.time.PeriodType; | |
import org.joda.time.format.DateTimeFormat; | |
import org.joda.time.format.DateTimeFormatter; | |
public class Main { | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
String tweetDate = "Wed Apr 17 01:30:00 -0000 2013"; | |
String tweetDate2 = "Tue Apr 16 20:35:00 -0000 2013"; | |
String tweetDate3 = "Mon Apr 15 20:30:00 -0000 2013"; | |
DateTimeFormatter dateFormater = DateTimeFormat.forPattern("E MMM d H:m:s Z Y").withLocale(new Locale("en")); | |
DateTime dt = dateFormater.parseDateTime(tweetDate); | |
DateTime dt2 = dateFormater.parseDateTime(tweetDate2); | |
DateTime dt3 = dateFormater.parseDateTime(tweetDate3); | |
DateTime agora = DateTime.now(); | |
System.out.println(dt3.toString("dd/MM/y HH:mm:ss")); | |
System.out.println(dt2.toString("dd/MM/y HH:mm:ss")); | |
System.out.println(dt.toString("dd/MM/y HH:mm:ss")); | |
System.out.println(agora.toString("dd/MM/y HH:mm:ss")); | |
Period p = new Period(dt, agora, PeriodType.yearMonthDayTime()); | |
Period p2 = new Period(dt2, agora, PeriodType.yearMonthDayTime()); | |
Period p3 = new Period(dt3, agora, PeriodType.yearMonthDayTime()); | |
printRelativeTime(p); | |
printRelativeTime(p2); | |
printRelativeTime(p3); | |
} | |
private static void printRelativeTime(Period p) { | |
if(p.getDays() < 31 && p.getDays() != 0){ | |
System.out.println(p.getDays()+" dias"); | |
} else if(p.getHours() < 24 && p.getHours() != 0){ | |
System.out.println(p.getHours()+" horas"); | |
}else if(p.getMinutes() < 60 && p.getMinutes() != 0){ | |
System.out.println(p.getMinutes()+" minutos"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
15/04/2013 17:30:00 Data 3
16/04/2013 17:35:00 Data 2
16/04/2013 22:30:00 Data 1
17/04/2013 00:00:48 Agora
1 horas Diff da Data 1
6 horas Diff da Data 2
1 dias Diff da Data 3