Date: Work with Moments in Time
Table of Contents
Java provides a useful and versatile Date
class in its java.time
package. This class allows us to represent moments in time and dates, and manipulate them however we want with just a few lines of code.
Java makes working with these a breeze.
Creating a Date
Creating a date is pretty easy. Simply create a Date
object and print it out:
JAVAimport java.util.Date;
public class Main {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.toString());
}
}
BASHSun Dec 15 00:00:00 UTC 2019
Date Formatting
You can format a date object using the SimpleDateFormat
class and calling its format()
method:
JAVAimport java.util.Date;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat format =
new SimpleDateFormat ("E yyyy-MM-dd 'at' hh:mm:ss a zzz");
System.out.println(format.format(now));
}
}
BASHSun 2019-12-15 at 00:00:00 AM UTC
If you're curious about what those characters do and if there are any others, here are all the characters that you can use when formatting your dates:
G
: Era (AD/BC)y
: Year in four digits (2020)M
: Month (June)d
: Day in month (17)h
: Hour from 1-12H
: Hour from 0-23m
: Minutes
: SecondS
: MillisecondE
: Day in week (Friday)D
: Day in year (100)F
: Day of week in month (2nd Friday in June)w
: Week in year (23)W
: Week in month (3)a
: AM/PMk
: Hour in day from 1-24K
: Hour from 0-11Z
: Timezone
Unix Time
Unix time is a concept in computer science that refers to the number of milliseconds that have elapsed since the arbitrarily decided midnight on January 1st, 1970.
Here's how to get that value in Java:
JAVAimport java.util.Date;
public class Main {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.getTime());
}
}
BASH1576146483561
Parsing Strings into Dates
When you have a string that represents a date, you can try and parse it into one:
JAVAimport java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String input = "1990-01-01";
try {
Date parsed = format.parse(input);
System.out.println(parsed.toString());
} catch (ParseException e) {
// error parsing
}
}
}
BASHMon Jan 01 00:00:00 UTC 1990
- Getting Started with TypeScript
- Getting Started with Solid
- Getting Started with Svelte
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with React
- Getting Started with Moon.js