Created
May 31, 2013 19:12
-
-
Save Alcar32/5687234 to your computer and use it in GitHub Desktop.
Show some features from joda time library. Url: http://joda-time.sourceforge.net/ maven: http://tinyurl.com/joda-maven-search-org
This file contains 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
package de.dailab.joda; | |
import java.text.SimpleDateFormat; | |
import java.util.TimeZone; | |
import org.joda.time.DateTime; | |
import org.joda.time.DateTimeZone; | |
import org.joda.time.Days; | |
import org.joda.time.Period; | |
import org.joda.time.format.PeriodFormatter; | |
import org.joda.time.format.PeriodFormatterBuilder; | |
public class JodaExamples { | |
final static SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd' - 'HH:mm:ss z"); | |
public static void main(String[] args) { | |
fmt.setTimeZone(TimeZone.getTimeZone("UTC")); | |
/* | |
* Snippet 1 | |
* | |
* Get the number of days between to DatesTimes. (ignore the current times of the DateTimes) | |
*/ | |
System.out.println("Snippet 1: "); | |
DateTime dt1 = new DateTime(2013, 5, 31, 14, 35, 1, DateTimeZone.UTC); | |
DateTime dt2 = new DateTime(2013, 6, 1, 15, 0, 1, DateTimeZone.UTC); | |
int daysBetween = Days.daysBetween(dt1.toDateMidnight(), dt2.toDateMidnight()).getDays(); | |
System.out.println(String.format("%s day(s) between dt1 and dt2.", daysBetween)); // 1 day | |
/* | |
* Snippet 2 | |
* | |
* Get a period between to DateTimes | |
*/ | |
System.out.println("\nSnippet 2: "); | |
DateTime dt3 = new DateTime(2013, 5, 31, 5, 30, 15, DateTimeZone.UTC); | |
DateTime dt4 = dt3.plusDays(1).plusHours(13).plusMinutes(5).plusSeconds(45); | |
Period period = new Period(dt3, dt4); | |
PeriodFormatter DDHHMMSSFormater = new PeriodFormatterBuilder() | |
.printZeroAlways() | |
.minimumPrintedDigits(2) | |
.appendDays().appendSeparator(" day(s) ") | |
.appendHours().appendSeparator(" hour(s) ") | |
.appendMinutes().appendSeparator(" minute(s) ") | |
.appendSeconds().appendLiteral(" second(s)") | |
.toFormatter(); | |
System.out.println(DDHHMMSSFormater.print(period)); | |
/* | |
* Snippet 3 | |
* | |
* Truncate the date from a DateTime | |
*/ | |
System.out.println("\nSnippet 3: "); | |
DateTime dt5 = new DateTime(2013, 5, 31, 15, 15, 15, DateTimeZone.UTC); | |
DateTime dt6 = new DateTime(2013, 5, 31, 0, 0, 1, DateTimeZone.UTC); | |
int timeOfDayinMilis = dt5.millisOfDay().get(); | |
DateTime dt7 = new DateTime(timeOfDayinMilis); | |
System.out.println("milis: "+dt7.getMillis()+" = "+fmt.format(dt7.toDate())); | |
timeOfDayinMilis = dt6.millisOfDay().get(); | |
DateTime dt8 = new DateTime(timeOfDayinMilis); | |
System.out.println("milis: "+dt8.getMillis()+" = "+fmt.format(dt8.toDate())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment