Convert java.util.Date to String
Convert a Date to a String using DateFormat#format
method:
String pattern = "MM/dd/yyyy HH:mm:ss";
// Create an instance of SimpleDateFormat used for formatting
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);
// Get the today date using Calendar object.
Date today = Calendar.getInstance().getTime();
// Using DateFormat format method we can create a string
// representation of a date with the defined format.
String todayAsString = df.format(today);
// Print the result!
System.out.println("Today is: " + todayAsString);
From http://www.kodejava.org/examples/86.html
Converting Date to String in SimpleDateFormat
To format current date you need to create a instance of Date
which represents current date and then format it using SimpleDateFormat
to string.
DateFormat dateFormat = new SimpleDateFormat("dd MM yyyy");
String currDateString = dateFormat.format(new Date());
System.out.println(currDateString);
How to get current timestamp in string format in Java? yyyy.MM.dd.HH.mm.ss
Replace
new Timestamp();
with
new java.util.Date()
because there is no default constructor for Timestamp
, or you can do it with the method:
new Timestamp(System.currentTimeMillis());
Convert Java Date from one format to another without converting it into string
Date
represents a single point in time. That's it, nothing more, nothing less. It does not contain any information about time zones.
Wed Jun 06 12:38:15 BST 2018
is the same Date
(instant) as Wed Jun 06 11:38:15 GMT 2018
, just in a different time zone. It's like the words "humans" and "homo sapians". They refer to the same species, they are just kind of in a different "format".
So you don't need to change the date in any way. You just need to format it differently. This is why formatters return String
s. Only String
s can represent one particular format of a date.
Java string to date conversion
That's the hard way, and those java.util.Date
setter methods have been deprecated since Java 1.1 (1997). Moreover, the whole java.util.Date
class was de-facto deprecated (discommended) since introduction of java.time
API in Java 8 (2014).
Simply format the date using DateTimeFormatter
with a pattern matching the input string (the tutorial is available here).
In your specific case of "January 2, 2010" as the input string:
- "January" is the full text month, so use the
MMMM
pattern for it - "2" is the short day-of-month, so use the
d
pattern for it. - "2010" is the 4-digit year, so use the
yyyy
pattern for it.
String string = "January 2, 2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2010-01-02
Note: if your format pattern happens to contain the time part as well, then use LocalDateTime#parse(text, formatter)
instead of LocalDate#parse(text, formatter)
. And, if your format pattern happens to contain the time zone as well, then use ZonedDateTime#parse(text, formatter)
instead.
Here's an extract of relevance from the javadoc, listing all available format patterns:
Symbol | Meaning | Presentation | Examples |
---|---|---|---|
G | era | text | AD; Anno Domini; A |
u | year | year | 2004; 04 |
y | year-of-era | year | 2004; 04 |
D | day-of-year | number | 189 |
M /L | month-of-year | number/text | 7; 07; Jul; July; J |
d | day-of-month | number | 10 |
Q /q | quarter-of-year | number/text | 3; 03; Q3; 3rd quarter |
Y | week-based-year | year | 1996; 96 |
w | week-of-week-based-year | number | 27 |
W | week-of-month | number | 4 |
E | day-of-week | text | Tue; Tuesday; T |
e /c | localized day-of-week | number/text | 2; 02; Tue; Tuesday; T |
F | week-of-month | number | 3 |
a | am-pm-of-day | text | PM |
h | clock-hour-of-am-pm (1-12) | number | 12 |
K | hour-of-am-pm (0-11) | number | 0 |
k | clock-hour-of-am-pm (1-24) | number | 0 |
H | hour-of-day (0-23) | number | 0 |
m | minute-of-hour | number | 30 |
s | second-of-minute | number | 55 |
S | fraction-of-second | fraction | 978 |
A | milli-of-day | number | 1234 |
n | nano-of-second | number | 987654321 |
N | nano-of-day | number | 1234000000 |
V | time-zone ID | zone-id | America/Los_Angeles; Z; -08:30 |
z | time-zone name | zone-name | Pacific Standard Time; PST |
O | localized zone-offset | offset-O | GMT+8; GMT+08:00; UTC-08:00; |
X | zone-offset 'Z' for zero | offset-X | Z; -08; -0830; -08:30; -083015; -08:30:15; |
x | zone-offset | offset-x | +0000; -08; -0830; -08:30; -083015; -08:30:15; |
Z | zone-offset | offset-Z | +0000; -0800; -08:00; |
How to convert date to string and to date again?
try this:
String DATE_FORMAT_NOW = "yyyy-MM-dd";
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String stringDate = sdf.format(date );
try {
Date date2 = sdf.parse(stringDate);
} catch(ParseException e){
//Exception handling
} catch(Exception e){
//handle exception
}
How to get the current date/time in Java
It depends on what form of date / time you want:
If you want the date / time as a single numeric value, then
System.currentTimeMillis()
gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Javalong
). This value is a delta from a UTC time-point, and is independent of the local time-zone1.If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:
new Date()
gives you aDate
object initialized with the current date / time. The problem is that theDate
API methods are mostly flawed ... and deprecated.Calendar.getInstance()
gives you aCalendar
object initialized with the current date / time, using the defaultLocale
andTimeZone
. Other overloads allow you to use a specificLocale
and/orTimeZone
. Calendar works ... but the APIs are still cumbersome.new org.joda.time.DateTime()
gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. https://stackoverflow.com/questions/6280829.)in Java 8, calling
java.time.LocalDateTime.now()
andjava.time.ZonedDateTime.now()
will give you representations2 for the current date / time.
Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations.
With Java 8 and later, the standard java.time
package is recommended. Joda time is now considered "obsolete", and the Joda maintainers are recommending that people migrate.3.
1 - System.currentTimeMillis()
gives the "system" time. While it is normal practice for the system clock to be set to (nominal) UTC, there will be a difference (a delta) between the local UTC clock and true UTC. The size of the delta depends on how well (and how often) the system's clock is synced with UTC.
2 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: "It cannot represent an instant on the time-line without additional information such as an offset or time-zone."
3 - Note: your Java 8 code won't break if you don't migrate, but the Joda codebase may eventually stop getting bug fixes and other patches. As of 2020-02, an official "end of life" for Joda has not been announced, and the Joda APIs have not been marked as Deprecated.
Related Topics
Spring Autowiring Using @Configurable
Java Jtextfield with Input Hint
How to Force Browser to Download File
Setting Jvm Heap Size at Runtime
What Code Folding Plugins Work on Eclipse 3.6
Java: How to Convert a Utc Timestamp to Local Time
How to Store Java Objects in Httpsession
How to Set Request Encoding in Tomcat
Compiler Error When Declaring a Variable Inside If Condition and No Curly Braces
Delete Item from Array and Shrink Array
Java Date - Insert into Database
How to Make My Swingworker Example Work Properly
Eclipse Windowbuilder, Overlapping JPAnels
How to Install the Jdk on Ubuntu Linux
Static Allocation in Java - Heap, Stack and Permanent Generation