Esempio n. 1
1
 /** @return formatted date string, hours in 24-hour format */
 public static String currentDate() {
   Date now = new Date();
   SimpleDateFormat df = new SimpleDateFormat();
   StringBuffer buf = new StringBuffer("(");
   df.applyPattern("MM/dd/yyyy");
   buf.append(df.format(now));
   buf.append(") (");
   df.applyPattern("HH:mm");
   buf.append(df.format(now));
   buf.append(")");
   buf.trimToSize();
   return buf.toString();
 }
  /**
   * This method is not thread safe. It has been modified from the original to not rely on global
   * time state. If a timestamp is in the future we return it as an absolute date string. Within the
   * same second we return 0s
   *
   * @param res resource
   * @param currentTimeMillis timestamp for offset
   * @param timestamp timestamp
   * @return the relative time string
   */
  static String getRelativeTimeString(Resources res, long currentTimeMillis, long timestamp) {
    final long diff = currentTimeMillis - timestamp;
    if (diff >= 0) {
      if (diff < DateUtils.MINUTE_IN_MILLIS) { // Less than a minute ago
        final int secs = (int) (diff / 1000);
        return res.getQuantityString(R.plurals.tw__time_secs, secs, secs);
      } else if (diff < DateUtils.HOUR_IN_MILLIS) { // Less than an hour ago
        final int mins = (int) (diff / DateUtils.MINUTE_IN_MILLIS);
        return res.getQuantityString(R.plurals.tw__time_mins, mins, mins);
      } else if (diff < DateUtils.DAY_IN_MILLIS) { // Less than a day ago
        final int hours = (int) (diff / DateUtils.HOUR_IN_MILLIS);
        return res.getQuantityString(R.plurals.tw__time_hours, hours, hours);
      } else {
        final Calendar now = Calendar.getInstance();
        now.setTimeInMillis(currentTimeMillis);
        final Calendar c = Calendar.getInstance();
        c.setTimeInMillis(timestamp);
        final Date d = new Date(timestamp);

        if (now.get(Calendar.YEAR) == c.get(Calendar.YEAR)) {
          // Same year
          RELATIVE_DATE_FORMAT.applyPattern(res.getString(R.string.tw__relative_date_format_short));
        } else {
          // Outside of our year
          RELATIVE_DATE_FORMAT.applyPattern(res.getString(R.string.tw__relative_date_format_long));
        }
        return RELATIVE_DATE_FORMAT.format(d);
      }
    }
    RELATIVE_DATE_FORMAT.applyPattern(res.getString(R.string.tw__relative_date_format_long));
    return RELATIVE_DATE_FORMAT.format(new Date(timestamp));
  }
Esempio n. 3
0
  /**
   * Get (Short) Date Format. The date format must parseable by org.compiere.grid.ed.MDocDate i.e.
   * leading zero for date and month
   *
   * @return date format MM/dd/yyyy - dd.MM.yyyy
   */
  public SimpleDateFormat getDateFormat() {
    if (m_dateFormat == null) {
      m_dateFormat = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, m_locale);
      String sFormat = m_dateFormat.toPattern();
      //	some short formats have only one M and/or d (e.g. ths US)
      if (sFormat.indexOf("MM") == -1 || sFormat.indexOf("dd") == -1) {
        sFormat = sFormat.replaceFirst("d+", "dd");
        sFormat = sFormat.replaceFirst("M+", "MM");
        //	log.finer(sFormat + " => " + nFormat);
        m_dateFormat.applyPattern(sFormat);
      }
      //	Unknown short format => use JDBC
      if (m_dateFormat.toPattern().length() != 8) m_dateFormat.applyPattern("yyyy-MM-dd");

      //	4 digit year
      if (m_dateFormat.toPattern().indexOf("yyyy") == -1) {
        sFormat = m_dateFormat.toPattern();
        String nFormat = "";
        for (int i = 0; i < sFormat.length(); i++) {
          if (sFormat.charAt(i) == 'y') nFormat += "yy";
          else nFormat += sFormat.charAt(i);
        }
        m_dateFormat.applyPattern(nFormat);
      }
      m_dateFormat.setLenient(true);
    }
    return m_dateFormat;
  } //  getDateFormat
Esempio n. 4
0
 public static void point(String path, String tag, String msg) {
   if (DeviceInfoUtil.isSDAva()) {
     Date date = new Date();
     SimpleDateFormat dateFormat = new SimpleDateFormat("", Locale.SIMPLIFIED_CHINESE);
     dateFormat.applyPattern("yyyy");
     path = path + dateFormat.format(date) + "/";
     dateFormat.applyPattern("MM");
     path += dateFormat.format(date) + "/";
     dateFormat.applyPattern("dd");
     path += dateFormat.format(date) + ".log";
     dateFormat.applyPattern("[yyyy-MM-dd HH:mm:ss]");
     String time = dateFormat.format(date);
     File file = new File(path);
     if (!file.exists()) createDipPath(path);
     BufferedWriter out = null;
     try {
       out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
       out.write(time + " " + tag + " " + msg + "\r\n");
     } catch (Exception e) {
       e.printStackTrace();
     } finally {
       try {
         if (out != null) {
           out.close();
         }
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }
Esempio n. 5
0
  /// Save Sell Data
  @Listen("onClick = #btncheckout")
  public void btncheckou_Click() {
    Date datem = new Date();
    java.text.SimpleDateFormat dfm = new java.text.SimpleDateFormat();
    dfm.applyPattern("MMMM");

    java.text.SimpleDateFormat dfy = new java.text.SimpleDateFormat();
    dfy.applyPattern("yyyy");

    String strdatem = String.format(dfm.format(datem));
    String strdatey = String.format(dfy.format(datem));

    for (int i = 0; i < pointcount; i++) {
      Sell selldata = new Sell();
      selldata.setDateselly(strdatey);
      selldata.setDatesellm(strdatem);
      selldata.setDatesell(datem);
      selldata.setNameproduct(nameproduct.get(i));
      selldata.setIdp(idpro.get(i));
      selldata.setIdqty(qty.get(i));
      selldata.setUnitprice(unitprice.get(i));
      selldata.setSellprice(price.get(i));
      selldata.setCusname(namecus.get(i));
      selldata.persist();
    }
    Sessions.getCurrent().setAttribute("name", null);
    Executions.sendRedirect("sellid.zul");
  }
 /** {@inheritDoc} */
 public void parameterize(final String parameter) {
   _customDateFormat = getDefaultDateFormat();
   if ((parameter == null) || (parameter.length() == 0)) {
     _customDateFormat.applyPattern(TIMESTAMP_PATTERN);
   } else {
     _customDateFormat.applyPattern(parameter);
   }
 }
Esempio n. 7
0
 /**
  * 获取当前日期的指定格式的字符串
  *
  * @param format 指定的日期时间格式,若为null或""则使用指定的格式"yyyy-MM-dd HH:MM"
  * @return
  */
 public static String getCurrentTime(String format) {
   if (format == null || format.trim().equals("")) {
     sdf.applyPattern(FORMAT_DATE_TIME);
   } else {
     sdf.applyPattern(format);
   }
   return sdf.format(new Date());
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout root =
        (LinearLayout) findViewById(android.R.id.list).getParent().getParent().getParent();
    View bar = LayoutInflater.from(this).inflate(R.layout.settings_toolbar, root, false);
    root.addView(bar, 0);
    Toolbar toolbar = (Toolbar) findViewById(R.id.settings_toolbar);
    toolbar.setNavigationOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            finish();
          }
        });

    addPreferencesFromResource(R.xml.prefs);

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    Resources res = getResources();

    ListPreference dateFormatPref = (ListPreference) findPreference("dateFormat");
    String[] dateFormatsValues = res.getStringArray(R.array.dateFormatsValues);
    String[] dateFormatsEntries = new String[dateFormatsValues.length];

    EditTextPreference customDateFormatPref =
        (EditTextPreference) findPreference("dateFormatCustom");
    customDateFormatPref.setDefaultValue(dateFormatsValues[0]);

    SimpleDateFormat sdformat = new SimpleDateFormat();
    for (int i = 0; i < dateFormatsValues.length; i++) {
      String value = dateFormatsValues[i];
      if ("custom".equals(value)) {
        sdformat.applyPattern(sp.getString("dateFormatCustom", dateFormatsValues[0]));
        String renderedCustom;
        try {
          renderedCustom = sdformat.format(SAMPLE_DATE);
        } catch (IllegalArgumentException e) {
          renderedCustom = res.getString(R.string.error_dateFormat);
        }
        dateFormatsEntries[i] =
            String.format(
                "%s:\n%s", res.getString(R.string.setting_dateFormatCustom), renderedCustom);
      } else {
        sdformat.applyPattern(value);
        dateFormatsEntries[i] = sdformat.format(SAMPLE_DATE);
      }
    }

    dateFormatPref.setDefaultValue(dateFormatsValues[0]);
    dateFormatPref.setEntries(dateFormatsEntries);
  }
Esempio n. 9
0
 /**
  * 根据Date,返回字符型日期格式
  *
  * @param date 日期对象
  * @param pattern 日期格式
  * @return {@link String}
  */
 public static String date2Str(Date date, String pattern) {
   if (date == null) {
     return null;
   }
   SimpleDateFormat sdf = new SimpleDateFormat();
   if (!AppUtils.isEmpty(pattern)) {
     sdf.applyPattern(pattern);
   } else {
     sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
   }
   return sdf.format(date);
 }
Esempio n. 10
0
 public static String getStringDataPorExtenso(Date data) {
   String extenso = "";
   SimpleDateFormat format = new SimpleDateFormat();
   format.applyPattern("dd");
   extenso += format.format(data);
   extenso += " de ";
   format.applyPattern("MMMMM");
   extenso += format.format(data);
   extenso += " de ";
   format.applyPattern("yyyy");
   extenso += format.format(data);
   return extenso;
 }
 @Override
 protected Converter getDateConverter(SimpleDateFormat dateFormat) {
   if (getInputFormat() != null) {
     dateFormat.applyPattern(getInputFormat());
   }
   return new PartialConverter(new MultipleFormatDateConverter(dateFormat));
 }
  private Date parseDateForFormat(final String format, final String date) {
    // test date string matches format structure using regex
    // - weed out illegal characters and enforce 4-digit year
    // - create the regex based on the local format string
    String reFormat =
        Pattern.compile("d+|M+|H+|m+")
            .matcher(Matcher.quoteReplacement(format))
            .replaceAll("\\\\d{1,2}");
    reFormat = Pattern.compile("y+").matcher(reFormat).replaceAll("\\\\d{4,}");
    if (Pattern.compile(reFormat).matcher(date).matches()) {

      // date string matches format structure,
      // - now test it can be converted to a valid date
      SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance();
      sdf.applyPattern(format);
      sdf.setTimeZone(timeZoneManager.getLoggedInUserTimeZone());
      sdf.setLenient(false);
      try {
        return sdf.parse(date);
      } catch (ParseException e) {
        return null;
      }
    }
    return null;
  }
Esempio n. 13
0
  public static Date parseDate(String dateString) throws Exception {
    SimpleDateFormat dateFormat = new SimpleDateFormat();
    String[] supportedFormats = {
      "dd MMM yyyy",
      "MM/dd/yyyy",
      "yyyy-MM-dd",
      "yy-MM-dd",
      "ddMMyyyy",
      "dd-MM-yyyy",
      "dd-MM-yy",
      "MM/dd/yy",
      "MMM/dd/yyyy",
      "yyyy-MM-dd HH:mm:ss",
      "yy-MM-dd HH:mm:ss",
      "dd-MM-yyyy HH:mm:ss",
      "dd-MM-yy HH:mm:ss",
      "MM/dd/yyyy HH:mm:ss",
      "MM/dd/yy HH:mm:ss"
    };

    for (String formatStr : supportedFormats) {
      try {
        dateFormat.applyPattern(formatStr);
        return dateFormat.parse(dateString);
      } catch (ParseException ex) {
      }
    }

    throw new Exception("Date string is not in a supported format: '" + dateString + "'.");
  }
Esempio n. 14
0
  public Filter cookFilter(Map map) throws InvalidDataException {
    Filter filter = new Filter();
    String[] ss = null;

    ss = (String[]) map.get("venderid");
    if (ss != null && ss.length > 0 && ss[0] != null && ss[0].length() > 0) {
      Values val_vender = new Values(ss);
      filter.add("p.venderid IN (" + val_vender.toString4String() + ") ");
    }

    ss = (String[]) map.get("month");
    if (ss != null && ss.length > 0) {
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat oSdf = new SimpleDateFormat("", Locale.ENGLISH);
      oSdf.applyPattern("yyyy-MM");
      try {
        cal.setTime(oSdf.parse(ss[0]));
      } catch (ParseException e) {
        throw new InvalidDataException(e);
      }
      int num2 = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

      filter.add(" (p.sdate) >= " + ValueAdapter.std2mdy(ss[0] + "-01"));
      filter.add(" (p.sdate) <= " + ValueAdapter.std2mdy(ss[0] + "-" + num2));
    }

    ss = (String[]) map.get("shopid");
    if (ss != null && ss.length > 0) {
      Values val_shopid = new Values(ss);
      filter.add("p.shopid IN (" + val_shopid.toString4String() + ") ");
    }
    return filter;
  }
Esempio n. 15
0
  /**
   * Creates or gets the pref node, creates an entry and then hooks it up as a listener. The current
   * value of the SimpleDateFormat because the default.
   *
   * @param simpleFormat the SimpleDateFormat object
   * @param section the section or category of the pref
   * @param pref the pref's name
   * @param attrName the actual attribute
   */
  public void registerInternal(
      final SimpleDateFormat simpleFormat,
      final String section,
      final String pref,
      final String attrName) {
    checkName(section, pref, attrName);

    String fullName = makeKey(section, pref, attrName);
    if (hash.get(fullName) == null) {
      String defValue = simpleFormat.toPattern();
      String prefVal = checkForPref(fullName, defValue);

      // -------------------------------------------------------------------------------
      // This corrects the formatter when it has a two digit year (Bug 7555)
      // still have not found out what is causing the problem.
      // -------------------------------------------------------------------------------
      if (prefVal.length() == 8 && StringUtils.countMatches(prefVal, "yyyy") == 0) {
        prefVal = StringUtils.replace(prefVal, "yy", "yyyy");
      }

      simpleFormat.applyPattern(prefVal);
      DateFormatCacheEntry dateEntry =
          new DateFormatCacheEntry(simpleFormat, fullName, prefVal, defValue);
      getPref().addChangeListener(fullName, dateEntry);
      hash.put(fullName, dateEntry);
    }
  }
Esempio n. 16
0
 public static Date parseDate(final String source, final String conversionPattern)
     throws ParseException {
   SimpleDateFormat sdf = DATE_FORMAT.get();
   sdf.applyPattern(conversionPattern);
   sdf.setLenient(false);
   return sdf.parse(source);
 }
Esempio n. 17
0
 /**
  * Verarbeitet den Klick auf den Button "speichern" aus der GUI, indem die GUI diese Methode
  * aufruft. Der Klick wird durch Delegation an die Spielstandklasse aufgelöst.
  */
 @SuppressWarnings("static-access")
 public void speichern() {
   if (lnkSpiel.istSpielZuEnde() == true) {
     if (this.gibSpielausgang(lnkSpielstand.gibSpieler1()) == Spielausgang.sieg) {
       lnkSpielstand.setzeSpielAusgang(Zustand.schwarz);
     } else if (this.gibSpielausgang(lnkSpielstand.gibSpieler1()) == Spielausgang.sieg) {
       lnkSpielstand.setzeSpielAusgang(Zustand.weiss);
     } else {
       lnkSpielstand.setzeSpielAusgang(Zustand.frei);
     }
   }
   lnkSpielstand.setzeKommentar(lnkGUI.speichern_gibKommentar());
   lnkSpielstand.setzeTitel(
       lnkSpielstand.gibSpieler1().gibName() + " vs " + lnkSpielstand.gibSpieler2().gibName());
   java.util.Date date = new java.util.Date();
   java.text.SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
   lnkSpielstand.setzeDatum(formatter.format(date));
   formatter.applyPattern("yyyy-MM-dd_hh-mm-ss");
   try {
     lnkSpielstand.speichern(this.SPEICHER_ORDNER + formatter.format(date) + ".xml");
     this.lnkGUI.speichern_erfolgreich();
   } catch (SpeichernException e) {
     this.lnkGUI.zeigeFehlerAn("Konnte nicht speichern!");
   }
 }
  private void addReviewsInView(LinearLayout llReviews) {
    LayoutInflater vi =
        (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    for (int i = 0; i < reviews.size(); i++) {
      Review review = reviews.get(i);

      View v = vi.inflate(R.layout.review_item, null);

      TextView tvReviewerName = (TextView) v.findViewById(R.id.tvReviewerName);
      tvReviewerName.setText(((SimpleUser) review.getReviewer()).getName());

      String PATTERN = "MMM yyyy";
      SimpleDateFormat dateFormat = new SimpleDateFormat();
      dateFormat.applyPattern(PATTERN);
      String date = dateFormat.format(review.getCreatedAt());
      TextView tvReviewDate = (TextView) v.findViewById(R.id.tvReviewDate);
      tvReviewDate.setText(date);

      TextView tvReviewText = (TextView) v.findViewById(R.id.tvReviewText);
      tvReviewText.setText(review.getReviewBody());

      llReviews.addView(
          v,
          new ViewGroup.LayoutParams(
              ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    }
  }
 /**
  * Formats the given date as a String.
  *
  * @return the formatted date string
  */
 public static String formatDate(Date date, String format, String timeZone) {
   if (date == null) return new String();
   SimpleDateFormat formatter = new SimpleDateFormat();
   formatter.applyPattern(format);
   formatter.setTimeZone(TimeZone.getTimeZone(timeZone));
   return formatter.format(date);
 }
 void testApplyPatternAndApplyLocalizedPatternWithLiteralPattern() {
   SimpleDateFormat sdf = new SimpleDateFormat();
   // BUG: Diagnostic contains: sdf.applyPattern("yyyy-MM-dd")
   sdf.applyPattern("YYYY-MM-dd");
   // BUG: Diagnostic contains: sdf.applyLocalizedPattern("yyyy-MM-dd")
   sdf.applyLocalizedPattern("YYYY-MM-dd");
 }
Esempio n. 21
0
  @Test
  public void regJDAccount() {
    SimpleDateFormat sdf = new SimpleDateFormat();
    String layout = "yyyyMMddHHmmss";
    sdf.applyPattern(layout);

    Calendar cl = Calendar.getInstance();

    String accountname = sdf.format(cl.getTime());

    webpage.homePage().navigateToJD("http://www.jd.com").register();
    webpage
        .regPage()
        .setAccountName("test" + accountname)
        .setPasswords("terryselenium_123")
        .submit();
    Assert.assertEquals(
        newregjd.getWebElement(NewRegLoc.regsuc, "test" + accountname).isDisplayed(), true);

    // newhome.navigateToJD("http://www.jd.com").register();
    // newregjd.setAccountName("test"+accountname).setPasswords("terryselenium_123").submit();
    // Assert.assertEquals(newregjd.getWebElement(NewRegLoc.regsuc,
    // "test"+accountname).isDisplayed(), true);

  }
Esempio n. 22
0
 public static String getDate() {
   SimpleDateFormat gmtFormat = new SimpleDateFormat();
   gmtFormat.applyPattern(DEFAULT_FORMAT);
   TimeZone gmtTime = TimeZone.getTimeZone("GMT");
   gmtFormat.setTimeZone(gmtTime);
   return gmtFormat.format(new Date());
 }
  /**
   * Construction du titre de l'excel
   *
   * @return
   */
  public String getExcelTitle() {
    StringBuffer buffer = new StringBuffer();

    String title = "Planning mensuelle des pilotes : ";
    Date date = (Date) session.get(PilotageConstants.PLANNING_SELECT_DATE);

    Calendar c = Calendar.getInstance();
    c.setTime(date);
    // String DateSelect = String.valueOf(c.get(Calendar.DATE));
    // DateSelect += "/" + String.valueOf(c.get(Calendar.MONTH)+1);
    // DateSelect += "/" + String.valueOf(c.get(Calendar.YEAR));

    SimpleDateFormat sdf = new SimpleDateFormat();
    sdf.setCalendar(c);
    sdf.applyPattern("MMMM");
    String libelleMois = sdf.format(c.getTime());
    String DateSelect = libelleMois.trim() + "_" + String.valueOf(c.get(Calendar.YEAR)).trim();

    buffer.append(title.trim());

    buffer.append(DateSelect.trim());

    buffer.append(".xls");
    return buffer.toString();
  }
Esempio n. 24
0
  private static Date parseDateWithLeniency(String str, String[] parsePatterns, boolean lenient)
      throws ParseException {
    if ((str == null) || (parsePatterns == null)) {
      throw new IllegalArgumentException("Date and Patterns must not be null");
    }
    SimpleDateFormat parser = new SimpleDateFormat();
    parser.setLenient(lenient);
    ParsePosition pos = new ParsePosition(0);
    for (int i = 0; i < parsePatterns.length; i++) {
      String pattern = parsePatterns[i];
      if (parsePatterns[i].endsWith("ZZ")) {
        pattern = pattern.substring(0, pattern.length() - 1);
      }
      parser.applyPattern(pattern);
      pos.setIndex(0);

      String str2 = str;
      if (parsePatterns[i].endsWith("ZZ")) {
        int signIdx = indexOfSignChars(str2, 0);
        while (signIdx >= 0) {
          str2 = reformatTimezone(str2, signIdx);
          signIdx = indexOfSignChars(str2, ++signIdx);
        }
      }
      Date date = parser.parse(str2, pos);
      if ((date != null) && (pos.getIndex() == str2.length())) {
        return date;
      }
    }
    throw new ParseException("Unable to parse the date: " + str, -1);
  }
 /**
  * Private method to handle birth date and age input.
  *
  * @param birthdate
  * @param dateformat
  * @param age
  * @return
  * @throws java.text.ParseException
  */
 private Date updateAge(String birthdate, String dateformat, String age)
     throws java.text.ParseException {
   SimpleDateFormat df = new SimpleDateFormat();
   if (!"".equals(dateformat)) {
     dateformat = dateformat.toLowerCase().replaceAll("m", "M");
   } else {
     dateformat = new String("MM/dd/yyyy");
   }
   df.applyPattern(dateformat);
   Calendar cal = Calendar.getInstance();
   cal.clear(Calendar.HOUR);
   cal.clear(Calendar.MINUTE);
   cal.clear(Calendar.SECOND);
   cal.clear(Calendar.MILLISECOND);
   if ("".equals(birthdate)) {
     if ("".equals(age)) {
       return cal.getTime();
     }
     try {
       cal.add(Calendar.YEAR, -(Integer.parseInt(age)));
     } catch (NumberFormatException nfe) {
       log.error("Error during adding date into calendar", nfe);
     }
     return cal.getTime();
   } else {
     cal.setTime(df.parse(birthdate));
   }
   return cal.getTime();
 }
 void testApplyPatternAndApplyLocalizedPatternWithConstantPattern() {
   SimpleDateFormat sdf = new SimpleDateFormat();
   // BUG: Diagnostic contains:
   sdf.applyPattern(WEEK_YEAR_PATTERN);
   // BUG: Diagnostic contains:
   sdf.applyLocalizedPattern(WEEK_YEAR_PATTERN);
 }
Esempio n. 27
0
 public String getFecha(Date date, String pattern) {
   sdfFormato.applyPattern(pattern);
   try {
     return sdfFormato.format(date);
   } catch (Exception e) {
     return "";
   }
 }
Esempio n. 28
0
  /**
   * Can make locale automatic!?
   *
   * @throws Exception
   */
  public static Node dateTimeElement(long time, Locale locale) throws Exception {

    try {
      Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
      Element dateNode = doc.createElement("formatted-date");

      // Works in most locales
      SimpleDateFormat df =
          (SimpleDateFormat)
              DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);

      Date d = new Date(time);
      df.applyPattern("MMMM");
      addChild(dateNode, "month", df.format(d));
      df.applyPattern("EEEE");
      addChild(dateNode, "day-of-week", df.format(d));
      df.applyPattern("yyyy");
      addChild(dateNode, "year", df.format(d));
      df.applyPattern("dd");
      addChild(dateNode, "day-of-month", df.format(d));
      df.applyPattern("h");
      addChild(dateNode, "hours", df.format(d));
      df.applyPattern("mm");
      addChild(dateNode, "minutes", df.format(d));
      df.applyPattern("a");
      addChild(dateNode, "am-pm", df.format(d));
      return dateNode;
    } catch (Exception ex) {
      throw new Exception(ex);
    }
  }
Esempio n. 29
0
 public static String format(
     final Date date, final boolean lenient, final String conversionPattern) {
   SimpleDateFormat sdf = DATE_FORMAT.get();
   if (conversionPattern != null) {
     sdf.applyPattern(conversionPattern);
   }
   sdf.setLenient(lenient);
   return sdf.format(date);
 }
Esempio n. 30
0
 /**
  * @param 将指定字符型日期转为日期型,,格式为指定的pattern
  * @return
  */
 public Date stringToDate(String string, String pattern) {
   SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance();
   format.applyPattern(pattern);
   try {
     return format.parse(string);
   } catch (ParseException e) {
     return null;
   }
 }