11

How can I transform a time value into YYYY-MM-DD format in Java?

long lastmodified = file.lastModified();
String lasmod =  /*TODO: Transform it to this format YYYY-MM-DD*/
Adrian Toman
  • 11,316
  • 5
  • 48
  • 62
Sergio del Amo
  • 76,835
  • 68
  • 152
  • 179
  • yes, i edited the question. Año = Year in spanish – Sergio del Amo Oct 22 '08 at 16:43
  • possible duplicate of [How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?](http://stackoverflow.com/questions/1459656/how-to-get-the-current-time-in-yyyy-mm-dd-hhmisec-millisecond-format-in-java) – Raedwald Apr 28 '14 at 12:22

5 Answers5

31

Something like:

Date lm = new Date(lastmodified);
String lasmod = new SimpleDateFormat("yyyy-MM-dd").format(lm);

See the javadoc for SimpleDateFormat.

sblundy
  • 60,628
  • 22
  • 121
  • 123
  • Just to state the obvious here, if you're doing this in the context of a long-lived object or in a loop, you probably want to construct the SimpleDateFormat object once and reuse it. – nsayer Oct 22 '08 at 16:52
  • @nsayer i would also like to state here, if you are doing a long lived object which is also in multi thread environment, you better create a new SimpleDateFormat everytime as it is not thread safe – PSo Nov 03 '20 at 07:36
  • You could synchronize the use of the SDF object in a multi-threaded environment. You still don't need to create it every time. – nsayer Jan 03 '21 at 03:44
4
final Date modDate = new Date(lastmodified);
final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
final String lasmod = f.format(modDate);

SimpleDateFormat

Lars Westergren
  • 2,119
  • 15
  • 25
3
String lasmod = new SimpleDateFormat("yyyy-MM-dd").format(new Date(lastmodified));

Look up the correct pattern you want for SimpleDateFormat... I may have included the wrong one from memory.

Instantsoup
  • 14,825
  • 5
  • 34
  • 41
1
Date d = new Date(lastmodified);
DateFormat form = new SimpleDateFormat("yyyy-MM-dd");
String lasmod = form.format(d);
Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
1

Try:

import java.text.SimpleDateFormat;
import java.util.Date;

long lastmodified = file.lastModified();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String lastmod =  format.format(new Date(lastmodified));
James Cooper
  • 2,320
  • 2
  • 23
  • 23