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
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js