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

How to use
Locale
in
java.util

Best Java code snippets using java.util.Locale (Showing top 20 results out of 45,198)

Refine searchRefine arrow

  • ResourceBundle
  • SimpleDateFormat
  • DateFormat
  • Date
  • MissingResourceException
  • Calendar
  • TimeZone
  • MessageFormat
  • DateFormatSymbols
origin: kaushikgopal/RxJava-Android-Samples

 private String _getCurrentTimestamp() {
  return new SimpleDateFormat("k:m:s:S a", Locale.getDefault()).format(new Date());
 }
}
origin: stackoverflow.com

 public class CustomCalendarSerializer extends JsonSerializer<Calendar> {

  public static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm");
  public static final Locale LOCALE_HUNGARIAN = new Locale("hu", "HU");
  public static final TimeZone LOCAL_TIME_ZONE = TimeZone.getTimeZone("Europe/Budapest");

  @Override
  public void serialize(Calendar value, JsonGenerator gen, SerializerProvider arg2)
      throws IOException, JsonProcessingException {
    if (value == null) {
      gen.writeNull();
    } else {
      gen.writeString(FORMATTER.format(value.getTime()));
    }
  }
}
origin: redisson/redisson

/**
 * Resolves locale code from locale.
 */
public static String resolveLocaleCode(Locale locale) {
  return resolveLocaleCode(locale.getLanguage(), locale.getCountry(), locale.getVariant());
}
origin: spring-projects/spring-framework

/**
 * Determine the RFC 3066 compliant language tag,
 * as used for the HTTP "Accept-Language" header.
 * @param locale the Locale to transform to a language tag
 * @return the RFC 3066 compliant language tag as {@code String}
 * @deprecated as of 5.0.4, in favor of {@link Locale#toLanguageTag()}
 */
@Deprecated
public static String toLanguageTag(Locale locale) {
  return locale.getLanguage() + (hasText(locale.getCountry()) ? "-" + locale.getCountry() : "");
}
origin: spring-projects/spring-framework

/**
 * Render the given locale as a text value for inclusion in a cookie.
 * <p>The default implementation calls {@link Locale#toString()}
 * or JDK 7's {@link Locale#toLanguageTag()}, depending on the
 * {@link #setLanguageTagCompliant "languageTagCompliant"} configuration property.
 * @param locale the locale to stringify
 * @return a String representation for the given locale
 * @since 4.3
 * @see #isLanguageTagCompliant()
 */
protected String toLocaleValue(Locale locale) {
  return (isLanguageTagCompliant() ? locale.toLanguageTag() : locale.toString());
}
origin: org.apache.logging.log4j/log4j-core

  /**
   * This test case validates date pattern before and after DST
   * Base Date : 12 Mar 2017
   * Daylight Savings started on : 02:00 AM
   */
  @Test
  public void testFormatLong_goingBackInTime_DST() {
    final Calendar instance = Calendar.getInstance(TimeZone.getTimeZone("EST"));
    instance.set(2017, 2, 12, 2, 0);
    final long now = instance.getTimeInMillis();
    final long start = now - TimeUnit.HOURS.toMillis(1);
    final long end = now + TimeUnit.HOURS.toMillis(1);

    for (final FixedFormat format : FixedFormat.values()) {
      if (format.getPattern().endsWith("n")) {
        continue; // cannot compile precise timestamp formats with SimpleDateFormat
      }
      final SimpleDateFormat simpleDF = new SimpleDateFormat(format.getPattern(), Locale.getDefault());
      final FixedDateFormat customTF = new FixedDateFormat(format, TimeZone.getDefault());
      for (long time = end; time > start; time -= 12345) {
        final String actual = customTF.format(time);
        final String expected = simpleDF.format(new Date(time));
        assertEquals(format + "(" + format.getPattern() + ")" + "/" + time, expected, actual);
      }
    }
  }
}
origin: knowm/XChange

public Date getTimestamp() {
 try {
  // Parse the timestamp into a Date object
  return new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.getDefault())
    .parse(timestamp);
 } catch (IllegalArgumentException | ParseException e) {
  // Return current Date
  return new Date();
 }
}
origin: stackoverflow.com

 private String getDateTime() {
    SimpleDateFormat dateFormat = new SimpleDateFormat(
        "yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    Date date = new Date();
    return dateFormat.format(date);
}

ContentValues values = new ContentValues();
values.put('username', 'ravitamada');
values.put('created_at', getDateTime());
// insert the row
long id = db.insert('users', null, values);
origin: stackoverflow.com

 Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
        Locale.getDefault());
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("Z");
String localTime = date.format(currentLocalTime);
origin: org.apache.commons/commons-lang3

private void validateSdfFormatFdpParseEquality(final String format, final Locale locale, final TimeZone tz, final DateParser fdp, final Date in, final int year, final Date cs) throws ParseException {
  final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
  sdf.setTimeZone(tz);
  if (format.equals(SHORT_FORMAT)) {
    sdf.set2DigitYearStart( cs );
  }
  final String fmt = sdf.format(in);
  try {
    final Date out = fdp.parse(fmt);
    assertEquals(locale.toString()+" "+in+" "+ format+ " "+tz.getID(), in, out);
  } catch (final ParseException pe) {
    if (year >= 1868 || !locale.getCountry().equals("JP")) {// LANG-978
      throw pe;
    }
  }
}
origin: stackoverflow.com

 public class Timeis {
  public static void main(String s[]) {
    long ts = 1022895271767L;
    SimpleDateFormat sdf = new SimpleDateFormat(" MMM d 'at' hh:mm a");
    // CREATE DateFormatSymbols WITH ALL SYMBOLS FROM (DEFAULT) Locale
    DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
    // OVERRIDE SOME symbols WHILE RETAINING OTHERS
    symbols.setAmPmStrings(new String[] { "am", "pm" });
    sdf.setDateFormatSymbols(symbols);
    String st = sdf.format(ts);
    System.out.println("time is " + st);
  }
}
origin: iSoron/uhabits

private static String getMonthAndYearString(CalendarDay day) {
  Calendar cal = Calendar.getInstance();
  cal.set(day.year, day.month, day.day);
  StringBuffer sbuf = new StringBuffer();
  sbuf.append(cal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()));
  sbuf.append(" ");
  sbuf.append(YEAR_FORMAT.format(cal.getTime()));
  return sbuf.toString();
}
origin: org.apache.commons/commons-lang3

private void testLocales(final String format, final boolean eraBC) throws Exception {
  final Calendar cal= Calendar.getInstance(GMT);
  cal.clear();
  cal.set(2003, Calendar.FEBRUARY, 10);
  if (eraBC) {
    cal.set(Calendar.ERA, GregorianCalendar.BC);
  }
  for(final Locale locale : Locale.getAvailableLocales() ) {
    // ja_JP_JP cannot handle dates before 1868 properly
    if (eraBC && locale.equals(FastDateParser.JAPANESE_IMPERIAL)) {
      continue;
    }
    final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
    final DateParser fdf = getInstance(format, locale);
    try {
      checkParse(locale, cal, sdf, fdf);
    } catch(final ParseException ex) {
      fail("Locale "+locale+ " failed with "+format+" era "+(eraBC?"BC":"AD")+"\n" + trimMessage(ex.toString()));
    }
  }
}
origin: checkstyle/checkstyle

/**
 * Gets the check message 'as is' from appropriate 'messages.properties'
 * file.
 *
 * @param messageBundle the bundle name.
 * @param messageKey the key of message in 'messages.properties' file.
 * @param arguments the arguments of message in 'messages.properties' file.
 * @return The message of the check with the arguments applied.
 */
private static String internalGetCheckMessage(
    String messageBundle, String messageKey, Object... arguments) {
  final ResourceBundle resourceBundle = ResourceBundle.getBundle(
      messageBundle,
      Locale.getDefault(),
      Thread.currentThread().getContextClassLoader(),
      new LocalizedMessage.Utf8Control());
  final String pattern = resourceBundle.getString(messageKey);
  final MessageFormat formatter = new MessageFormat(pattern, Locale.ROOT);
  return formatter.format(arguments);
}
origin: com.h2database/h2

String getStartDateTime() {
  if (startDateTime == null) {
    SimpleDateFormat format = new SimpleDateFormat(
        "EEE, d MMM yyyy HH:mm:ss z", new Locale("en", ""));
    format.setTimeZone(DateTimeUtils.UTC);
    startDateTime = format.format(System.currentTimeMillis());
  }
  return startDateTime;
}
origin: wangdan/AisenWeiBo

private void updateDisplay(boolean announce) {
  /*if (mDayOfWeekView != null) {
    mDayOfWeekView.setText(mCalendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG,
        Locale.getDefault()).toUpperCase(Locale.getDefault()));
  }
  mSelectedMonthTextView.setText(mCalendar.getDisplayName(Calendar.MONTH, Calendar.SHORT,
      Locale.getDefault()).toUpperCase(Locale.getDefault()));*/
  if (this.mDayOfWeekView != null){
    this.mCalendar.setFirstDayOfWeek(mWeekStart);
    this.mDayOfWeekView.setText(mDateFormatSymbols.getWeekdays()[this.mCalendar.get(Calendar.DAY_OF_WEEK)].toUpperCase(Locale.getDefault()));
  }
  this.mSelectedMonthTextView.setText(mDateFormatSymbols.getMonths()[this.mCalendar.get(Calendar.MONTH)].toUpperCase(Locale.getDefault()));
  mSelectedDayTextView.setText(DAY_FORMAT.format(mCalendar.getTime()));
  mYearView.setText(YEAR_FORMAT.format(mCalendar.getTime()));
  // Accessibility.
  long millis = mCalendar.getTimeInMillis();
  mAnimator.setDateMillis(millis);
  int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR;
  String monthAndDayText = DateUtils.formatDateTime(getActivity(), millis, flags);
  mMonthAndDayView.setContentDescription(monthAndDayText);
  if (announce) {
    flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
    String fullDateText = DateUtils.formatDateTime(getActivity(), millis, flags);
    Utils.tryAccessibilityAnnounce(mAnimator, fullDateText);
  }
}
origin: guardianproject/haven

private String generateLog () {
  StringBuilder mEventLog = new StringBuilder();
  setTitle("Event @ " + mEvent.getStartTime().toLocaleString());
  for (EventTrigger eventTrigger : mEvent.getEventTriggers()) {
    mEventLog.append("Event Triggered @ ").append(
         new SimpleDateFormat(Utils.DATE_TIME_PATTERN,
            Locale.getDefault()).format(eventTrigger.getTriggerTime())).append("\n");
    String sType = eventTrigger.getStringType(this);
    mEventLog.append("Event Type: ").append(sType);
    mEventLog.append("\n==========================\n");
  }
  return mEventLog.toString();
}
origin: javax.el/javax.el-api

locale = Locale.getDefault();
ResourceBundle rb = null;
if (null == (rb = (ResourceBundle)
    threadMap.get(locale.toString()))) {
  rb = ResourceBundle.getBundle("javax.el.PrivateMessages",
                 locale);
  threadMap.put(locale.toString(), rb);
    result = rb.getString(messageId);
    if (null != params) {
      result = MessageFormat.format(result, params);
origin: iSoron/uhabits

private void updateDisplay(boolean announce) {
  if (mDayOfWeekView != null) {
    mDayOfWeekView.setText(mCalendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG,
        Locale.getDefault()).toUpperCase(Locale.getDefault()));
  }
  mSelectedMonthTextView.setText(mCalendar.getDisplayName(Calendar.MONTH, Calendar.SHORT,
      Locale.getDefault()).toUpperCase(Locale.getDefault()));
  mSelectedDayTextView.setText(DAY_FORMAT.format(mCalendar.getTime()));
  mYearView.setText(YEAR_FORMAT.format(mCalendar.getTime()));
  // Accessibility.
  long millis = mCalendar.getTimeInMillis();
  mAnimator.setDateMillis(millis);
  int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR;
  String monthAndDayText = DateUtils.formatDateTime(getActivity(), millis, flags);
  mMonthAndDayView.setContentDescription(monthAndDayText);
  if (announce) {
    flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
    String fullDateText = DateUtils.formatDateTime(getActivity(), millis, flags);
    Utils.tryAccessibilityAnnounce(mAnimator, fullDateText);
  }
}
origin: xalan/xalan

   throws MissingResourceException
Locale locale = Locale.getDefault();
 return (ListResourceBundle)ResourceBundle.getBundle(className, locale);
  return (ListResourceBundle)ResourceBundle.getBundle(
   className, new Locale("en", "US"));
  throw new MissingResourceException(
   "Could not load any resource bundles." + className, className, "");
java.utilLocale

Javadoc

Locale represents a language/country/variant combination. Locales are used to alter the presentation of information such as numbers or dates to suit the conventions in the region they describe.

The language codes are two-letter lowercase ISO language codes (such as "en") as defined by ISO 639-1. The country codes are two-letter uppercase ISO country codes (such as "US") as defined by ISO 3166-1. The variant codes are unspecified.

Note that Java uses several deprecated two-letter codes. The Hebrew ("he") language code is rewritten as "iw", Indonesian ("id") as "in", and Yiddish ("yi") as "ji". This rewriting happens even if you construct your own Locale object, not just for instances returned by the various lookup methods.

Available locales

This class' constructors do no error checking. You can create a Locale for languages and countries that don't exist, and you can create instances for combinations that don't exist (such as "de_US" for "German as spoken in the US").

Note that locale data is not necessarily available for any of the locales pre-defined as constants in this class except for en_US, which is the only locale Java guarantees is always available.

It is also a mistake to assume that all devices have the same locales available. A device sold in the US will almost certainly support en_US and es_US, but not necessarily any locales with the same language but different countries (such as en_GB or es_ES), nor any locales for other languages (such as de_DE). The opposite may well be true for a device sold in Europe.

You can use Locale#getDefault to get an appropriate locale for the user of the device you're running on, or Locale#getAvailableLocales to get a list of all the locales available on the device you're running on.

Locale data

Note that locale data comes solely from ICU. User-supplied locale service providers (using the java.text.spi or java.util.spi mechanisms) are not supported.

Here are the versions of ICU (and the corresponding CLDR and Unicode versions) used in various Android releases:

Android 1.5 (Cupcake)/Android 1.6 (Donut)/Android 2.0 (Eclair) ICU 3.8 CLDR 1.5 Unicode 5.0
Android 2.2 (Froyo) ICU 4.2 CLDR 1.7 Unicode 5.1
Android 2.3 (Gingerbread)/Android 3.0 (Honeycomb) ICU 4.4 CLDR 1.8 Unicode 5.2
Android 4.0 (Ice Cream Sandwich) ICU 4.6 CLDR 1.9 Unicode 6.0
Android 4.1 (Jelly Bean) ICU 4.8 CLDR 2.0 Unicode 6.0
Android 4.3 (Jelly Bean MR2) ICU 50 CLDR 22.1 Unicode 6.2
Android 4.4 (KitKat) ICU 51 CLDR 23 Unicode 6.2

Be wary of the default locale

Note that there are many convenience methods that automatically use the default locale, but using them may lead to subtle bugs.

The default locale is appropriate for tasks that involve presenting data to the user. In this case, you want to use the user's date/time formats, number formats, rules for conversion to lowercase, and so on. In this case, it's safe to use the convenience methods.

The default locale is not appropriate for machine-readable output. The best choice there is usually Locale.US – this locale is guaranteed to be available on all devices, and the fact that it has no surprising special cases and is frequently used (especially for computer-computer communication) means that it tends to be the most efficient choice too.

A common mistake is to implicitly use the default locale when producing output meant to be machine-readable. This tends to work on the developer's test devices (especially because so many developers use en_US), but fails when run on a device whose user is in a more complex locale.

For example, if you're formatting integers some locales will use non-ASCII decimal digits. As another example, if you're formatting floating-point numbers some locales will use ',' as the decimal point and '.' for digit grouping. That's correct for human-readable output, but likely to cause problems if presented to another computer ( Double#parseDouble can't parse such a number, for example). You should also be wary of the String#toLowerCase and String#toUpperCase overloads that don't take a Locale: in Turkey, for example, the characters 'i' and 'I' won't be converted to 'I' and 'i'. This is the correct behavior for Turkish text (such as user input), but inappropriate for, say, HTTP headers.

Most used methods

  • getDefault
    Gets the current value of the default locale for the specified Category for this instance of the Jav
  • <init>
    There's a circular dependency between toLowerCase/toUpperCase and Locale.US. Work around this by avo
  • getLanguage
    Returns the language code of this Locale.Note: ISO 639 is not a stable standard— some languages' cod
  • toString
    Returns a string representation of this Locale object, consisting of language, country, variant, scr
  • getCountry
    Returns the country/region code for this locale, which should either be the empty string, an upperca
  • equals
    Returns true if object is a locale with the same language, country and variant.
  • setDefault
    Sets the default locale for this instance of the Java Virtual Machine. This does not affect the host
  • getVariant
    Returns the variant code for this locale.
  • forLanguageTag
  • getDisplayName
    Returns this locale's language name, country name, and variant, localized to locale. The exact outpu
  • getAvailableLocales
    Returns an array of all installed locales. The returned array represents the union of locales suppor
  • toLanguageTag
  • getAvailableLocales,
  • toLanguageTag,
  • hashCode,
  • getDisplayLanguage,
  • getDisplayCountry,
  • getISO3Language,
  • getISO3Country,
  • getDisplayVariant,
  • getISOLanguages,
  • getISOCountries

Popular in Java

  • Running tasks concurrently on multiple threads
  • setRequestProperty (URLConnection)
  • orElseThrow (Optional)
    Return the contained value, if present, otherwise throw an exception to be created by the provided s
  • scheduleAtFixedRate (ScheduledExecutorService)
  • HttpServer (com.sun.net.httpserver)
    This class implements a simple HTTP server. A HttpServer is bound to an IP address and port number a
  • Format (java.text)
    The base class for all formats. This is an abstract base class which specifies the protocol for clas
  • Comparator (java.util)
    A Comparator is used to compare two objects to determine their ordering with respect to each other.
  • JarFile (java.util.jar)
    JarFile is used to read jar entries and their associated data from jar files.
  • Collectors (java.util.stream)
  • JLabel (javax.swing)
  • Best IntelliJ plugins
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