Last active
December 20, 2018 15:44
-
-
Save trevor-atlas/fe2442f49bea16a7e070f188c0e33196 to your computer and use it in GitHub Desktop.
Useful Java date and time one liners and functions
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
// get the current year as an int, E.G: 2018 | |
Calendar.getInstance().get(Calendar.YEAR); | |
/* get date as iso 8601 string | |
* public static Instant now() | |
* Obtains the current instant from the system clock. | |
* This will query the system UTC clock to obtain the current instant. | |
* | |
* public String toString() | |
* A string representation of this instant using ISO-8601 representation. | |
* The format used is the same as DateTimeFormatter.ISO_INSTANT. | |
*/ | |
Instant.now().toString(); | |
Instant.now() // Capture the current moment in UTC with a resolution as fines nanoseconds but usually in microseconds or milliseconds. | |
.truncatedTo(ChronoUnit.MINUTES) // Lop off any seconds or fractional second, to get a value in whole minutes. | |
.toString(); // Generate a String in standard ISO 8601 format where a `T` separates the year-month-day from the hour-minute-second, and the `Z` on the end for “Zulu” means UTC. | |
// java.util.Date date -> ISO 8601 string | |
Instant.ofEpochMilli(date.getTime()).toString(); | |
String d = new Date().toInstant().toString(); | |
ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT); | |
public int getNumDaysInMonth(int month) { | |
int year = Calendar.getInstance().get(Calendar.YEAR); | |
YearMonth yearMonthObject = YearMonth.of(year, month); | |
return yearMonthObject.lengthOfMonth(); | |
} | |
// OffsetDateTime to Joda DateTime | |
private DateTime convertDate(OffsetDateTime offsetDateTime) { | |
long epochMilli = offsetDateTime.toInstant().toEpochMilli(); | |
Date date = new Date(epochMilli); | |
DateTime dateTime = new DateTime(date); | |
return dateTime; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment