Tabnine Logo
SimpleDateFormat
Code IndexAdd Tabnine to your IDE (free)

How to use
SimpleDateFormat
in
java.text

Best Java code snippets using java.text.SimpleDateFormat (Showing top 20 results out of 74,097)

Refine searchRefine arrow

  • DateFormat
  • Date
  • Calendar
  • TimeZone
  • GregorianCalendar
canonical example by Tabnine

public boolean isDateExpired(String input, Date expiration) throws ParseException {
 DateFormat dateFormat = new SimpleDateFormat ("dd/MM/yyyy");
 Date date = dateFormat.parse(input);
 return date.after(expiration);
}
origin: stackoverflow.com

 SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));

//Local time zone   
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

//Time in GMT
return dateFormatLocal.parse( dateFormatGmt.format(new Date()) );
origin: org.testng/testng

static String timeAsGmt() {
 SimpleDateFormat sdf = new SimpleDateFormat();
 sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
 sdf.applyPattern("dd MMM yyyy HH:mm:ss z");
 return sdf.format(Calendar.getInstance().getTime());
}
origin: apache/incubator-dubbo

  @Override
  public Object decode(Object jv) throws IOException {
    if (jv instanceof String) {
      try {
        return new SimpleDateFormat(DATE_FORMAT).parse((String) jv);
      } catch (ParseException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
      }
    }
    if (jv instanceof Number) {
      return new Date(((Number) jv).longValue());
    }
    return (Date) null;
  }
};
origin: spring-projects/spring-framework

private DateFormat newDateFormat() {
  SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US);
  dateFormat.setTimeZone(GMT);
  return dateFormat;
}
origin: alibaba/druid

public static String toString(java.util.Date date) {
  if (date == null) {
    return null;
  }
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  return format.format(date);
}
origin: spring-projects/spring-framework

private long parseDateHeader(String name, String value) {
  for (String dateFormat : DATE_FORMATS) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);
    simpleDateFormat.setTimeZone(GMT);
    try {
      return simpleDateFormat.parse(value).getTime();
    }
    catch (ParseException ex) {
      // ignore
    }
  }
  throw new IllegalArgumentException("Cannot parse date value '" + value + "' for '" + name + "' header");
}
origin: stackoverflow.com

 // Create an instance of SimpleDateFormat used for formatting 
// the string representation of date (month/day/year)
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

// Get the date today 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 reportDate = df.format(today);

// Print what date is today!
System.out.println("Report Date: " + reportDate);
origin: weibocom/motan

private void printStartInfo() {
  Date currentDate = new Date();
  Calendar calendar = Calendar.getInstance();
  calendar.setTime(currentDate);
  calendar.add(Calendar.SECOND, runTime);
  Date finishDate = calendar.getTime();
  StringBuilder startInfo = new StringBuilder(dateFormat.format(currentDate));
  startInfo.append(" ready to start client benchmark");
  startInfo.append(", concurrent num is ").append(concurrents);
  startInfo.append(", the benchmark will end at ").append(dateFormat.format(finishDate));
  System.out.println(startInfo.toString());
}
origin: blynkkk/blynk-server

/**
 * Sets the Date and Cache headers for the HTTP Response
 *
 * @param response
 *            HTTP response
 * @param fileToCache
 *            file to extract content type
 */
private static void setDateAndCacheHeaders(io.netty.handler.codec.http.HttpResponse response, File fileToCache) {
  SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
  dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
  // Date header
  Calendar time = new GregorianCalendar();
  response.headers().set(DATE, dateFormatter.format(time.getTime()));
  // Add cache headers
  time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
  response.headers()
      .set(EXPIRES, dateFormatter.format(time.getTime()))
      .set(CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS)
      .set(LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified())));
}
origin: north2016/T-MVP

public static List<String> getOldWeekDays() {
  final Calendar c = Calendar.getInstance();
  String[] months = new String[8];
  for (int i = 0; i < 8; i++) {
    months[i] = new SimpleDateFormat("MM.dd").format(new Date(c
        .getTimeInMillis()));
    c.add(Calendar.DAY_OF_MONTH, -1);
  }
  return Arrays.asList(months);
}
origin: stackoverflow.com

 Calendar c = Calendar.getInstance();
c.setTime(new Date(yourmilliseconds));
c.set(Calendar.MILLISECOND, 0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm.ss.SSS'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(c.getTime()));
origin: stackoverflow.com

 Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp!
String format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(now);
String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).format(now);
String format3 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH).format(now);

System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
origin: apache/incubator-dubbo

  private String getTimeoutMessage(boolean scan) {
    long nowTimestamp = System.currentTimeMillis();
    return (sent > 0 ? "Waiting server-side response timeout" : "Sending request timeout in client-side")
        + (scan ? " by scan timer" : "") + ". start time: "
        + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start))) + ", end time: "
        + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())) + ","
        + (sent > 0 ? " client elapsed: " + (sent - start)
        + " ms, server elapsed: " + (nowTimestamp - sent)
        : " elapsed: " + (nowTimestamp - start)) + " ms, timeout: "
        + timeout + " ms, request: " + request + ", channel: " + channel.getLocalAddress()
        + " -> " + channel.getRemoteAddress();
  }
}
origin: stackoverflow.com

UTC = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(UTC);
final Calendar c = new GregorianCalendar(UTC);
c.set(1, 0, 1, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
BEGINNING_OF_TIME = c.getTime();
c.setTime(new Date(Long.MAX_VALUE));
END_OF_TIME = c.getTime();
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
sdf.setTimeZone(UTC);
System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));
origin: apache/rocketmq

public String getCurTime() {
  String fromTimeZone = "GMT+8";
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  Date date = new Date();
  format.setTimeZone(TimeZone.getTimeZone(fromTimeZone));
  String chinaDate = format.format(date);
  return chinaDate;
}
origin: blynkkk/blynk-server

/**
 * Sets the Date header for the HTTP response
 *
 * @param response
 *            HTTP response
 */
private static void setDateHeader(FullHttpResponse response) {
  SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
  dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
  Calendar time = new GregorianCalendar();
  response.headers().set(DATE, dateFormatter.format(time.getTime()));
}
origin: stackoverflow.com

 final DateFormat format = new SimpleDateFormat("E. M/d");
final String dateStr = "Thu. 03/01";
final Date date = format.parse(dateStr);

GregorianCalendar gregory = new GregorianCalendar();
gregory.setTime(date);

XMLGregorianCalendar calendar = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar(
      gregory);
origin: elastic/elasticsearch-hadoop

@Test
public void testCalendar() {
  Date d = new Date(0);
  Calendar cal = Calendar.getInstance();
  cal.setTime(d);
  assertThat(jdkTypeToJson(cal), containsString(new SimpleDateFormat("yyyy-MM-dd").format(d)));
}
origin: kiegroup/jbpm

protected List<TimePeriod> parseHolidays() {
  String holidaysString = businessCalendarConfiguration.getProperty(HOLIDAYS);
  List<TimePeriod> holidays = new ArrayList<TimePeriod>();
  int currentYear = Calendar.getInstance().get(Calendar.YEAR);
  if (holidaysString != null) {
    String[] hPeriods = holidaysString.split(",");
    SimpleDateFormat sdf = new SimpleDateFormat(businessCalendarConfiguration.getProperty(HOLIDAY_DATE_FORMAT, "yyyy-MM-dd"));
    for (String hPeriod : hPeriods) {
      boolean addNextYearHolidays = false;
          Calendar tmpFrom = new GregorianCalendar();
          if (timezone != null) {
            tmpFrom.setTimeZone(TimeZone.getTimeZone(timezone));
          tmpFrom.setTime(sdf.parse(fromTo[0]));
          tmpTo.setTime(sdf.parse(fromTo[1]));
            tmpFrom.setTime(sdf.parse(fromTo[0]));
            tmpTo.setTime(sdf.parse(fromTo[1]));
          c.setTime(sdf.parse(fromTo[0]));
          holidays.add(new TimePeriod(sdf.parse(fromTo[0]), c.getTime()));
            tmp.setTime(sdf.parse(fromTo[0]));
java.textSimpleDateFormat

Javadoc

Formats and parses dates in a locale-sensitive manner. Formatting turns a Date into a String, and parsing turns a String into a Date.

Time Pattern Syntax

You can supply a Unicode UTS #35 pattern describing what strings are produced/accepted, but almost all callers should use DateFormat#getDateInstance, DateFormat#getDateTimeInstance, or DateFormat#getTimeInstance to get a ready-made instance suitable for the user's locale. In cases where the system does not provide a suitable pattern, see android.text.format.DateFormat#getBestDateTimePattern which lets you specify the elements you'd like in a pattern and get back a pattern suitable for any given locale.

The main reason you'd create an instance this class directly is because you need to format/parse a specific machine-readable format, in which case you almost certainly want to explicitly ask for Locale#US to ensure that you get ASCII digits (rather than, say, Arabic digits). (See "Be wary of the default locale".) The most useful non-localized pattern is "yyyy-MM-dd HH:mm:ss.SSSZ", which corresponds to the ISO 8601 international standard date format.

To specify the time format, use a time pattern string. In this string, any character from 'A' to 'Z' or 'a' to 'z' is treated specially. All other characters are passed through verbatim. The interpretation of each of the ASCII letters is given in the table below. ASCII letters not appearing in the table are reserved for future use, and it is an error to attempt to use them.

The number of consecutive copies (the "count") of a pattern character further influences the format, as shown in the table. For fields of kind "number", the count is the minimum number of digits; shorter values are zero-padded to the given width and longer values overflow it.

Symbol Meaning Kind Example
D day in year (Number) 189
E day of week (Text) E/ EE/ EEE:Tue, EEEE:Tuesday, EEEEE:T
F day of week in month (Number) 2 (2nd Wed in July)
G era designator (Text) AD
H hour in day (0-23) (Number) 0
K hour in am/pm (0-11) (Number) 0
L stand-alone month (Text) L:1 LL:01 LLL:Jan LLLL:January LLLLL:J
M month in year (Text) M:1 MM:01 MMM:Jan MMMM:January MMMMM:J
S fractional seconds (Number) 978
W week in month (Number) 2
Z time zone (RFC 822) (Time Zone) Z/ ZZ/ ZZZ:-0800 ZZZZ:GMT-08:00 ZZZZZ:-08:00
a am/pm marker (Text) PM
c stand-alone day of week (Text) c/ cc/ ccc:Tue, cccc:Tuesday, ccccc:T
d day in month (Number) 10
h hour in am/pm (1-12) (Number) 12
k hour in day (1-24) (Number) 24
m minute in hour (Number) 30
s second in minute (Number) 55
w week in year (Number) 27
y year (Number) yy:10 y/ yyy/ yyyy:2010
z time zone (Time Zone) z/ zz/ zzz:PST zzzz:Pacific Standard Time
' escape for text (Delimiter) 'Date=':Date=
'' single quote (Literal) 'o''clock':o'clock

Fractional seconds are handled specially: they're zero-padded on the right.

The two pattern characters L and c are ICU-compatible extensions, not available in the RI or in Android before Android 2.3 (Gingerbread, API level 9). These extensions are necessary for correct localization in languages such as Russian that make a grammatical distinction between, say, the word "June" in the sentence "June" and in the sentence "June 10th"; the former is the stand-alone form, the latter the regular form (because the usual case is to format a complete date). The relationship between Eand c is equivalent, but for weekday names.

Five-count patterns (such as "MMMMM") used for the shortest non-numeric representation of a field were introduced in Android 4.3 (Jelly Bean MR2, API level 18).

When two numeric fields are directly adjacent with no intervening delimiter characters, they constitute a run of adjacent numeric fields. Such runs are parsed specially. For example, the format "HHmmss" parses the input text "123456" to 12:34:56, parses the input text "12345" to 1:23:45, and fails to parse "1234". In other words, the leftmost field of the run is flexible, while the others keep a fixed width. If the parse fails anywhere in the run, then the leftmost field is shortened by one character, and the entire run is parsed again. This is repeated until either the parse succeeds or the leftmost field is one character in length. If the parse still fails at that point, the parse of the run fails.

See #set2DigitYearStart for more about handling two-digit years.

Sample Code

If you're formatting for human use, you should use an instance returned from DateFormat as described above. This code:

 
DateFormat[] formats = new DateFormat[] { 
DateFormat.getDateInstance(), 
DateFormat.getDateTimeInstance(), 
DateFormat.getTimeInstance(), 
}; 
for (DateFormat df : formats) { 
System.out.println(df.format(new Date(0))); 
} 

Produces this output when run on an en_US device in the America/Los_Angeles time zone:

 
Dec 31, 1969 
Dec 31, 1969 4:00:00 PM 
4:00:00 PM 
And will produce similarly appropriate localized human-readable output on any user's system.

If you're formatting for machine use, consider this code:

 
String[] formats = new String[] { 
"yyyy-MM-dd", 
"yyyy-MM-dd HH:mm", 
"yyyy-MM-dd HH:mmZ", 
"yyyy-MM-dd HH:mm:ss.SSSZ", 
"yyyy-MM-dd'T'HH:mm:ss.SSSZ", 
}; 
for (String format : formats) { 
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US); 
System.out.format("%30s %s\n", format, sdf.format(new Date(0))); 
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); 
System.out.format("%30s %s\n", format, sdf.format(new Date(0))); 
} 

Which produces this output when run in the America/Los_Angeles time zone:

 
yyyy-MM-dd 1969-12-31 
yyyy-MM-dd 1970-01-01 
yyyy-MM-dd HH:mm 1969-12-31 16:00 
yyyy-MM-dd HH:mm 1970-01-01 00:00 
yyyy-MM-dd HH:mmZ 1969-12-31 16:00-0800 
yyyy-MM-dd HH:mmZ 1970-01-01 00:00+0000 
yyyy-MM-dd HH:mm:ss.SSSZ 1969-12-31 16:00:00.000-0800 
yyyy-MM-dd HH:mm:ss.SSSZ 1970-01-01 00:00:00.000+0000 
yyyy-MM-dd'T'HH:mm:ss.SSSZ 1969-12-31T16:00:00.000-0800 
yyyy-MM-dd'T'HH:mm:ss.SSSZ 1970-01-01T00:00:00.000+0000 

As this example shows, each SimpleDateFormat instance has a TimeZone. This is because it's called upon to format instances of Date, which represents an absolute time in UTC. That is, Date does not carry time zone information. By default, SimpleDateFormat will use the system's default time zone. This is appropriate for human-readable output (for which, see the previous sample instead), but generally inappropriate for machine-readable output, where ambiguity is a problem. Note that in this example, the output that included a time but no time zone cannot be parsed back into the original Date. For this reason it is almost always necessary and desirable to include the timezone in the output. It may also be desirable to set the formatter's time zone to UTC (to ease comparison, or to make logs more readable, for example). It is often best to avoid formatting completely when writing dates/times in machine-readable form. Simply sending the "Unix time" as a longor as the string corresponding to the long is cheaper and unambiguous, and can be formatted any way the recipient deems appropriate.

Synchronization

SimpleDateFormat is not thread-safe. Users should create a separate instance for each thread.

Most used methods

  • <init>
  • format
  • parse
    Parses a date from the specified string starting at the index specified by position. If the string i
  • setTimeZone
  • toPattern
    Returns the pattern of this simple date format using non-localized pattern characters.
  • setLenient
  • applyPattern
    Changes the pattern of this simple date format to the specified pattern which uses non-localized pat
  • clone
    Returns a new SimpleDateFormat with the same pattern and properties as this simple date format.
  • setCalendar
  • getTimeZone
  • set2DigitYearStart
    Sets the date which is the start of the one hundred year period for two-digit year values.When parsi
  • getDateTimeInstance
  • set2DigitYearStart,
  • getDateTimeInstance,
  • parseObject,
  • getDateInstance,
  • toLocalizedPattern,
  • getDateFormatSymbols,
  • setDateFormatSymbols,
  • getTimeInstance,
  • applyLocalizedPattern,
  • getCalendar

Popular in Java

  • Start an intent from android
  • getResourceAsStream (ClassLoader)
  • startActivity (Activity)
  • getSupportFragmentManager (FragmentActivity)
  • FileReader (java.io)
    A specialized Reader that reads from a file in the file system. All read requests made by calling me
  • MalformedURLException (java.net)
    This exception is thrown when a program attempts to create an URL from an incorrect specification.
  • Queue (java.util)
    A collection designed for holding elements prior to processing. Besides basic java.util.Collection o
  • TimerTask (java.util)
    The TimerTask class represents a task to run at a specified time. The task may be run once or repeat
  • Executor (java.util.concurrent)
    An object that executes submitted Runnable tasks. This interface provides a way of decoupling task s
  • BoxLayout (javax.swing)
  • Top plugins for WebStorm
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now