Java 类java.text.SimpleDateFormat 实例源码

项目:openjdk-jdk10    文件:CalendarRegression.java   
/**
 * Prove that GregorianCalendar is proleptic (it used to cut off
 * at 45 BC, and not have leap years before then).
 */
public void Test4125892() {
    Locale locale = Locale.getDefault();
    if (!TestUtils.usesGregorianCalendar(locale)) {
        logln("Skipping this test because locale is " + locale);
        return;
    }

    GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
    DateFormat fmt = new SimpleDateFormat("MMMM d, yyyy G");
    cal.clear();
    cal.set(ERA, GregorianCalendar.BC);
    cal.set(YEAR, 81); // 81 BC is a leap year (proleptically)
    cal.set(MONTH, FEBRUARY);
    cal.set(DATE, 28);
    cal.add(DATE, 1);
    if (cal.get(DATE) != 29
            || !cal.isLeapYear(-80)) { // -80 == 81 BC
        errln("Calendar not proleptic");
    }
}
项目:dubbox-hystrix    文件:Envs.java   
public void index(Map<String, Object> context) throws Exception {
    Map<String, String> properties = new TreeMap<String, String>();
    StringBuilder msg = new StringBuilder();
    msg.append("Version: ");
    msg.append(Version.getVersion(Envs.class, "2.2.0"));
    properties.put("Registry", msg.toString());
    String address = NetUtils.getLocalHost();
    properties.put("Host", NetUtils.getHostName(address) + "/" + address);
    properties.put("Java", System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version"));
    properties.put("OS", System.getProperty("os.name") + " "
            + System.getProperty("os.version"));
    properties.put("CPU", System.getProperty("os.arch", "") + ", "
            + String.valueOf(Runtime.getRuntime().availableProcessors()) + " cores");
    properties.put("Locale", Locale.getDefault().toString() + "/"
            + System.getProperty("file.encoding"));
    properties.put("Uptime", formatUptime(ManagementFactory.getRuntimeMXBean().getUptime()) 
            + " From " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z").format(new Date(ManagementFactory.getRuntimeMXBean().getStartTime())) 
            + " To " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z").format(new Date()));
    context.put("properties", properties);
}
项目:jobManage    文件:UtilHelper.java   
public static Integer countDiffDay(String startDate, String endDate) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance(); 
    long fTime = 0;
    long oTime = 0;
      try {
    cal.setTime(sdf.parse(startDate));
       fTime = cal.getTimeInMillis();

       cal.setTime(sdf.parse(endDate));    
       oTime = cal.getTimeInMillis();  
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}    

      long between_days=(oTime-fTime)/(1000*3600*24); 
    return Integer.parseInt(String.valueOf(between_days));
  }
项目:urule    文件:WriteJsonServletHandler.java   
protected void writeObjectToJson(HttpServletResponse resp,Object obj) throws ServletException, IOException{
    resp.setHeader("Access-Control-Allow-Origin", "*");
    resp.setContentType("text/json");
    resp.setCharacterEncoding("UTF-8");
    ObjectMapper mapper=new ObjectMapper();
    mapper.setSerializationInclusion(Inclusion.NON_NULL);
    mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);
    mapper.setDateFormat(new SimpleDateFormat(Configure.getDateFormat()));
    OutputStream out = resp.getOutputStream();
    try {
        mapper.writeValue(out, obj);
    } finally {
        out.flush();
        out.close();
    }
}
项目:atsd-web-test    文件:AdminServiceTest.java   
private long getCurrentTime() {
    long currentTime = 0;
    NTPUDPClient client = new NTPUDPClient();
    client.setDefaultTimeout(WAIT_FOR_SERVER_RESPONSE);
    try {
        client.open();
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM dd yyyy HH:mm:ss.SSS zzz");
        for (String server : NTP_SERVERS) {
            try {
                InetAddress ioe = InetAddress.getByName(server);
                TimeInfo info = client.getTime(ioe);
                TimeStamp ntpTime = TimeStamp.getNtpTime(info.getReturnTime());
                return ntpTime.getTime();
            } catch (Exception e2) {
                System.out.println("Can't get response from server: " + server + ".");
            }
        }
    } catch (SocketException se) {
        System.out.println("Can't open client session");
    } finally {
        client.close();
    }
    return currentTime;
}
项目:hands-on-api-proxy    文件:PhotoDetailFragment.java   
private String getPhotoCaption(Photo photo) {
    String day = getResources().getString(R.string.pod_missing_date);
    String sep = getResources().getString(R.string.pod_caption_sep);
    String exp = getResources().getString(R.string.pod_missing_desc);


    if (photo != null) {
        SimpleDateFormat formatter = new SimpleDateFormat(getResources().getString(R.string.pod_caption_date_fmt));
        if (photo.getDate() != null) {
            day = formatter.format(photo.getDate());
        }
        if (photo.getDesc() != null) {
            exp = photo.getDesc();
        }
    }

    if (day.equals("?")) {
        return exp;
    } else{
        return day + sep + exp;
    }
}
项目:MyCourses    文件:KonsolRandevuUygulamasi.java   
public void randevuAra() throws IOException
{
    SimpleDateFormat format_n=new SimpleDateFormat("dd/MM/yyyy");
    System.out.println("Bulmak istedi�iniz randevu ad�n� yerini yada tarihini girin:");
    String aranan= cin.readLine();

    for(Randevular obj:randevular){
        int dogrulaAd = obj.compareTo(aranan);
        if(dogrulaAd==0){
            System.out.println("----BULUNAN RANDEVU----");
            System.out.println(obj.getRandevuAdi()+"\n"+obj.getRandevuYeri()+"\n"
                     +format_n.format(obj.getRandevuTarihi()));

        }else{
            System.out.println("----ARANAN RANDEVU KAYITLARDA YOK----");
        }

    }
}
项目:openNaEF    文件:ConfigUtil.java   
@Override
public boolean validate(XMLConfiguration conf) {
    value = conf.getString(paramName);
    if (value == null) {
        if (isNullOk) return true;
        return false;
    }
    try {
        DateFormat format = new SimpleDateFormat(DATE_STRING_FORMAT);
        format.parse(value);
        return true;
    } catch (ParseException e) {
        log.debug("", e);
        validateFalse();
    }
    return false;
}
项目:PI-Web-API-Client-Java-Android    文件:ApiClient.java   
/**
 * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android.
 */
private void initDatetimeFormat() {
    String formatWithTimeZone = null;
    if (IS_ANDROID) {
        if (ANDROID_SDK_VERSION >= 18) {
            // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18)
            formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ";
        }
    } else if (JAVA_VERSION >= 1.7) {
        // The time zone format "XXX" is available since Java 1.7
        formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
    }
    if (formatWithTimeZone != null) {
        this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone);
        // NOTE: Use the system's default time zone (mainly for datetime formatting).
    } else {
        // Use a common format that works across all systems.
        this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        // Always use the UTC time zone as we are using a constant trailing "Z" here.
        this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    }
}
项目:joanne    文件:Sorter.java   
private void findByDate(String param){
    SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
    SimpleDateFormat df2 = new SimpleDateFormat("dd-MMM-yyyy");
    LastModifiedFileComparator c = new LastModifiedFileComparator();

    Date file = new Date();
    String d = df.format(file);
    sorted.clear();

    List<File> l1 = new ArrayList<>();
    toSort.stream().filter((image) -> ( df2.format(new File(image).lastModified()).equals(d))).forEach((image) -> {
        l1.add(new File(image));
    });

    List<File> f = c.sort(l1);
    f.forEach(x ->{
        sorted.add(x.getAbsolutePath());
    });
}
项目:OpenDA    文件:WflowBmiBridgeTest.java   
public void testGetTimeData() throws Exception {
    initializeModel();

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS Z");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

        double timeStep = model.getTimeStep();
        assertEquals(24 * 3600.0, timeStep);

        String timeUnits = model.getTimeUnits();
        assertEquals("seconds since 1970-01-01 00:00:00.0 00:00", timeUnits);

        double startTime = model.getStartTime();
        assertEquals("2012-01-01 00:00:00 000 +0000", dateFormat.format((long) startTime * 1000));
        assertEquals("2012-01-01 00:00:00 000 +0000", dateFormat.format(Time.mjdToMillies(TimeUtils.udUnitsTimeToMjd(startTime, timeUnits))));

        double endTime = model.getEndTime();
        assertEquals("2012-01-21 00:00:00 000 +0000", dateFormat.format((long) endTime * 1000));
        assertEquals("2012-01-21 00:00:00 000 +0000", dateFormat.format(Time.mjdToMillies(TimeUtils.udUnitsTimeToMjd(endTime, timeUnits))));

        assertEquals(model.getStartTime(), model.getCurrentTime());
}
项目:openjdk-jdk10    文件:DateFormatProviderImpl.java   
private DateFormat getInstance(int dateStyle, int timeStyle, Locale locale) {
    if (locale == null) {
        throw new NullPointerException();
    }

    SimpleDateFormat sdf = new SimpleDateFormat("", locale);
    Calendar cal = sdf.getCalendar();
    try {
        String pattern = LocaleProviderAdapter.forType(type)
            .getLocaleResources(locale).getDateTimePattern(timeStyle, dateStyle,
                                                           cal);
        sdf.applyPattern(pattern);
    } catch (MissingResourceException mre) {
        // Specify the fallback pattern
        sdf.applyPattern("M/d/yy h:mm a");
    }

    return sdf;
}
项目:parabuild-ci    文件:IntervalCategoryLabelGeneratorTests.java   
/**
 * Tests the equals() method.
 */
public void testEquals() {

    IntervalCategoryLabelGenerator g1 = new IntervalCategoryLabelGenerator();
    IntervalCategoryLabelGenerator g2 = new IntervalCategoryLabelGenerator();
    assertTrue(g1.equals(g2));
    assertTrue(g2.equals(g1));

    g1 = new IntervalCategoryLabelGenerator("{3} - {4}", new DecimalFormat("0.000"));
    assertFalse(g1.equals(g2));
    g2 = new IntervalCategoryLabelGenerator("{3} - {4}", new DecimalFormat("0.000"));
    assertTrue(g1.equals(g2));

    g1 = new IntervalCategoryLabelGenerator("{3} - {4}", new SimpleDateFormat("d-MMM"));
    assertFalse(g1.equals(g2));
    g2 = new IntervalCategoryLabelGenerator("{3} - {4}", new SimpleDateFormat("d-MMM"));
    assertTrue(g1.equals(g2));

}
项目:EosCommander    文件:EosChainInfo.java   
public String getTimeAfterHeadBlockTime(int diffInMilSec) {
    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    try {
        Date date = sdf.parse( this.headBlockTime);

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add( Calendar.MILLISECOND, diffInMilSec);
        date = c.getTime();

        return sdf.format(date);

    } catch (ParseException e) {
        e.printStackTrace();
        return this.headBlockTime;
    }
}
项目:Matisse    文件:MediaStoreCompat.java   
private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp =
            new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String imageFileName = String.format("JPEG_%s.jpg", timeStamp);
    File storageDir;
    if (mCaptureStrategy.isPublic) {
        storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
    } else {
        storageDir = mContext.get().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    }

    // Avoid joining path components manually
    File tempFile = new File(storageDir, imageFileName);

    // Handle the situation that user's external storage is not ready
    if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
        return null;
    }

    return tempFile;
}
项目:Sanxing    文件:MyDuration.java   
public static long durationFromAtoB(LocalDateTime A,LocalDateTime B)
{
    String aString=LocalDateTime_to_String(A);
    // reform the aString
    String bString=LocalDateTime_to_String(B);
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    long diff=0;
    try
    {
        Date aDate=df.parse(aString);
        Date bDate=df.parse(bString);
        diff = bDate.getTime() - aDate.getTime();//这样得到的差值是微秒级别
    }
    catch(ParseException e)
    {
        e.printStackTrace();
    }
    return diff;
}
项目:neoscada    文件:XAxisDynamicRenderer.java   
protected DateFormat createFormatInstance ( final long timeRange )
{
    if ( hasFormat () )
    {
        try
        {
            return new SimpleDateFormat ( this.format );
        }
        catch ( final IllegalArgumentException e )
        {
            return DateFormat.getInstance ();
        }
    }
    else
    {
        return Helper.makeFormat ( timeRange );
    }
}
项目:iBase4J    文件:TypeParseUtil.java   
private static Object sqlDate2Obj(Object value, String type, String format) {
    String fromType = "Date";
    Date dte = (Date) value;
    if ("String".equalsIgnoreCase(type) || DataType.STRING.equalsIgnoreCase(type)) {
        if (format == null || format.length() == 0) {
            return dte.toString();
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(new java.util.Date(dte.getTime()));
        }
    } else if ("Date".equalsIgnoreCase(type) || DataType.DATE.equalsIgnoreCase(type)) {
        return new java.util.Date(dte.getTime());
    } else if ("java.sql.Date".equalsIgnoreCase(type)) {
        return value;
    } else if ("Time".equalsIgnoreCase(type) || DataType.TIME.equalsIgnoreCase(type)) {
        throw new DataParseException("Conversion from " + fromType + " to " + type + " not currently supported");
    } else if ("Timestamp".equalsIgnoreCase(type) || DataType.TIMESTAMP.equalsIgnoreCase(type)) {
        return new Timestamp(dte.getTime());
    } else {
        throw new DataParseException(String.format(support, fromType, type));
    }
}
项目:Automekanik    文件:TeDhenat.java   
private void filtro(){
    try {
        String sql;
        if (!txtPuna.getText().isEmpty())
            sql = "select * from Punet where konsumatori = '" + e.getText() + "' and lower(lloji) like lower('%" + txtPuna.getText() + "%')";
        else
            sql = "select * from Punet where konsumatori = '" + e.getText() + "'";

        Connection conn = DriverManager.getConnection(CON_STR, "test", "test");
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        ObservableList<punetTbl> data = FXCollections.observableArrayList();
        Format format = new SimpleDateFormat("dd/MM/yyyy");
        String s = "";
        while (rs.next()){
            s = format.format(rs.getDate("data"));
            data.add(new punetTbl(rs.getInt("id"), rs.getString("lloji"),
                    s, rs.getFloat("qmimi"), rs.getString("pershkrimi"), rs.getString("kryer"), rs.getString("makina")));
        }
        table.setItems(data);
        conn.close();
    }catch (Exception ex){
        ex.printStackTrace();
    }
}
项目:MKAPP    文件:AdapterDns.java   
@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
    // Get values
    long time = cursor.getLong(colTime);
    String qname = cursor.getString(colQName);
    String aname = cursor.getString(colAName);
    String resource = cursor.getString(colResource);
    int ttl = cursor.getInt(colTTL);

    long now = new Date().getTime();
    boolean expired = (time + ttl < now);
    view.setBackgroundColor(expired ? colorExpired : Color.TRANSPARENT);

    // Get views
    TextView tvTime = (TextView) view.findViewById(R.id.tvTime);
    TextView tvQName = (TextView) view.findViewById(R.id.tvQName);
    TextView tvAName = (TextView) view.findViewById(R.id.tvAName);
    TextView tvResource = (TextView) view.findViewById(R.id.tvResource);
    TextView tvTTL = (TextView) view.findViewById(R.id.tvTTL);

    // Set values
    tvTime.setText(new SimpleDateFormat("dd HH:mm").format(time));
    tvQName.setText(qname);
    tvAName.setText(aname);
    tvResource.setText(resource);
    tvTTL.setText("+" + Integer.toString(ttl / 1000));
}
项目:PaoMovie    文件:ImageUtils.java   
/**
 * 生成输出文件路径
 *
 * @param mediaStorageDir 存储的文件
 * @param fileType        类型
 * @param format          生成的文件名的格式
 * @return
 */
public static String getFilePath(File mediaStorageDir, int fileType, String format) {
    String timeStamp = new SimpleDateFormat(format)
            .format(new Date());
    String filePath = mediaStorageDir.getPath() + File.separator;
    if (fileType == TYPE_FILE_IMAGE) {
        filePath += ("IMG_" + timeStamp + ".jpg");
    } else if (fileType == TYPE_FILE_VEDIO) {
        filePath += ("VIDEO_" + timeStamp + ".mp4");
    } else {
        return null;
    }
    return filePath;
}
项目:asura    文件:JmxServer.java   
/**
 * 
 * 启动JMXConnectorServer
 *
 * @author zhangshaobin
 * @created 2012-12-28 下午4:00:59
 *
 * @throws IOException
 */
private void start() {
    if (null != server)
        return;
    try {
        //          platformServer = ManagementFactory.getPlatformMBeanServer();
        server = MBeanServerFactory.createMBeanServer("Asura");
        JMXServiceURL url = new JMXServiceURL("jmxmp", null, port);
        //          JMXServiceURL platformUrl = new JMXServiceURL("jmxmp", null, 9021);
        //          platformConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(platformUrl, null, platformServer);
        //          platformConnectorServer.start();
        //          System.out.println("JMX PlatformServer started! Used port 9020.");
        connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
        connectorServer.start();
        System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss] ").format(new Date())
                + "JMX Server started! used port:" + port);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss] ").format(new Date())
                + "JMX Server started failed!" + " " + e.getMessage());
        System.exit(1);
    }
}
项目:uavstack    文件:DateTimeHelper.java   
public static String getToday(String format) {

        String result = "";
        try {
            Date today = new Date();
            SimpleDateFormat simpleFormat = new SimpleDateFormat(format);
            result = simpleFormat.format(today);
        }
        catch (Exception e) {
        }
        return result;
    }
项目:spline    文件:FileBindingAdapters.java   
/**
 * Simple binding adapter to convert long timestamp to a human-readable date.
 * @param view
 * @param date
 */
@BindingAdapter("android:text")
public static void setText(TextView view, long date) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    String formatted = format.format(date);
    view.setText(formatted);
}
项目:tulingchat    文件:DateUtil.java   
/**
 * 两个时间之间的时间集合 格式自定义
 */
public static List<String> getDatesBetweenTwoDateByStyle(String sDate, String eDate,
    String dateStyle) {
  List<String> returnList = new ArrayList<>();
  SimpleDateFormat sdf = new SimpleDateFormat(dateStyle);
  Date beginDate = null;
  Date endDate = null;
  Calendar cal = Calendar.getInstance();
  try {
    beginDate = sdf.parse(sDate);
    sDate = sdf.format(beginDate);
    endDate = sdf.parse(eDate);
    eDate = sdf.format(endDate);
    returnList.add(sDate);// 把开始时间加入集合
    // 使用给定的 Date 设置此 Calendar 的时间
    cal.setTime(beginDate);
    boolean bContinue = true;
    while (bContinue) {
      // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
      cal.add(Calendar.DAY_OF_MONTH, 1);
      // 测试此日期是否在指定日期之后
      if (endDate.after(cal.getTime())) {
        Date time = cal.getTime();
        returnList.add(sdf.format(time));
      } else {
        break;
      }
    }
    returnList.add(eDate);// 把结束时间加入集合
  } catch (ParseException e) {
    e.printStackTrace();
  }
  return returnList;
}
项目:Equella    文件:Utils.java   
/**
 * On a parse error, re-throw
 * 
 * @param java.util.Date
 * @return dateAsString
 */
public static String formatDateToPlainString(@Nullable Date date, SimpleDateFormat dateFormat)
{
    if( date == null )
    {
        return null;
    }
    dateFormat.setTimeZone(TimeZone.getDefault());
    return dateFormat.format(date);
}
项目:parabuild-ci    文件:AbstractCommandBasedSourceControl.java   
/**
 * Syncs to a given change list number
 */
public final void syncToChangeList(final int changeListID) throws BuildException, CommandStoppedException, AgentFailureException {
  // check if we have a command
  final String syncToChangeListCommand = getSettingValue(SourceControlSetting.COMMAND_VCS_SYNC_TO_CHANGE_LIST_COMMAND, null);
  if (StringUtils.isBlank(syncToChangeListCommand)) return;

  // execute
  FileSystemSourceControl.CommandBasedSourceControlCommand command = null;
  try {
    final ChangeList changeList = configManager.getChangeList(changeListID);
    final Date changeListDate = changeList.getCreatedAt();
    final Agent agent = getCheckoutDirectoryAwareAgent();
    command = new CommandBasedSourceControlCommand(agent);
    command.setCommand(syncToChangeListCommand);
    command.addEnvironment(PARAMETER_PARABUILD_CHANGE_LIST_TIMESTAMP, Long.toString(changeListDate.getTime()));
    command.addEnvironment(PARAMETER_PARABUILD_CHANGE_LIST_DATETIME, new SimpleDateFormat("yyyyMMddHHmmss").format(changeListDate));
    command.addEnvironment(getCommonEnvironment());
    command.execute();
    this.lastSyncDate = (Date) changeListDate.clone();
  } catch (IOException e) {
    throw processException(e);
  } finally {
    cleanup(command);
  }
}
项目:oldmonk    文件:ReporterAPI.java   
public String getReportGenerationDateAndTime()
{
    Calendar currentdate = Calendar.getInstance();

    String reportGenerationDateAndTime = null;
    DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm a z");
    reportGenerationDateAndTime = formatter.format(currentdate.getTime());

    TimeZone obj = TimeZone.getTimeZone("IST");

    formatter.setTimeZone(obj);
    reportGenerationDateAndTime = formatter.format(currentdate.getTime());

    return reportGenerationDateAndTime;
}
项目:storj_hoststats_app    文件:StorjNodeDetailActivity.java   
private String getDate(long timeStamp){
    try{
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Date netDate = (new Date(timeStamp));
        return sdf.format(netDate);
    }
    catch(Exception ex){
        return "xx";
    }
}
项目:ClouldReader    文件:TimeUtil.java   
public static String timeFormatStr(String time) {
    //
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    Date date = null;
    try {
        // 将给定的字符串中的日期提取出来
        date = sdf.parse(time);
    } catch (Exception e) {
        DebugUtil.debug("--时间解析-->", "错误");
        return time;
    }
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return sdf1.format(date);
}
项目:rongyunDemo    文件:DateUtils.java   
/**
 * 得到当前时间
 * @param dateFormat 时间格式
 * @return 转换后的时间格式
 */
public static String getStringToday(String dateFormat) {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    String dateString = formatter.format(currentTime);
    return dateString;
}
项目:OpenJSharp    文件:DerOutputStream.java   
/**
 * Private helper routine for marshalling a DER UTC/Generalized
 * time/date value. If the tag specified is not that for UTC Time
 * then it defaults to Generalized Time.
 * @param d the date to be marshalled
 * @param tag the tag for UTC Time or Generalized Time
 */
private void putTime(Date d, byte tag) throws IOException {

    /*
     * Format the date.
     */

    TimeZone tz = TimeZone.getTimeZone("GMT");
    String pattern = null;

    if (tag == DerValue.tag_UtcTime) {
        pattern = "yyMMddHHmmss'Z'";
    } else {
        tag = DerValue.tag_GeneralizedTime;
        pattern = "yyyyMMddHHmmss'Z'";
    }

    SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.US);
    sdf.setTimeZone(tz);
    byte[] time = (sdf.format(d)).getBytes("ISO-8859-1");

    /*
     * Write the formatted date.
     */

    write(tag);
    putLength(time.length);
    write(time);
}
项目:Backmemed    文件:FileManager.java   
public void writeCrash(String alah) {
    try {
        DateFormat format = new SimpleDateFormat("MM_dd_yyyy-HH_mm_ss");
        Date date = new Date();
        File file = new File(xdolfDir.getAbsolutePath(), "crashlog-".concat(format.format(date)).concat(".xen"));
        BufferedWriter outWrite = new BufferedWriter(new FileWriter(file));
        outWrite.write(alah);
        outWrite.close();
    } catch (Exception error) {
        System.out.println("Ohh the irony.");
    }
}
项目:jetfuel    文件:DateAdapter.java   
/**
 * Parses a date with a specific format pattern;
 * 
 * @param input
 * @param format
 * @return
 * @throws ParseException
 */
public static final Date parse(String input, String format) throws ParseException {
    if (input == null || input.isEmpty())
        return null;

    if (input.length() > format.length())
        input = input.substring(0, format.length());
    else if (input.length() < format.length())
        format = format.substring(0, input.length());

    return new SimpleDateFormat(format).parse(input);

}
项目:GitHub    文件:GoldPresenter.java   
@Override
public void getGoldData(String type) {
    mType = type;
    currentPage = 0;
    totalList.clear();
    Flowable<List<GoldListBean>> list = mRetrofitHelper.fetchGoldList(type, NUM_EACH_PAGE, currentPage++)
            .compose(RxUtil.<GoldHttpResponse<List<GoldListBean>>>rxSchedulerHelper())
            .compose(RxUtil.<List<GoldListBean>>handleGoldResult());

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -3);

    Flowable<List<GoldListBean>> hotList = mRetrofitHelper.fetchGoldHotList(type,
            new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()), NUM_HOT_LIMIT)
            .compose(RxUtil.<GoldHttpResponse<List<GoldListBean>>>rxSchedulerHelper())
            .compose(RxUtil.<List<GoldListBean>>handleGoldResult());

    addSubscribe(Flowable.concat(hotList, list)
            .subscribeWith(new CommonSubscriber<List<GoldListBean>>(mView) {
                @Override
                public void onNext(List<GoldListBean> goldListBean) {
                    if (isHotList) {
                        isHotList = false;
                        totalList.addAll(goldListBean);
                    } else {
                        isHotList = true;
                        totalList.addAll(goldListBean);
                        mView.showContent(totalList);
                    }
                }
            })
    );
}
项目:yyox    文件:DateUtils.java   
public static long strToTimeStamp(String time) {
    SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
    Date date = null;
    try {
        //处理时间中带回车字符的问题
        time = time.replace("\n"," ");
        time = time.replace("\t","");
        date = format.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date.getTime() / 1000;
}
项目:tangyuan2    文件:TimeOnlyTypeHandler.java   
@Override
public void appendLog(StringBuilder builder, Date parameter, DatabaseDialect dialect) {
    // if (DatabaseDialect.MYSQL == dialect) {
    // builder.append('\'');
    // builder.append((null != parameter) ? new SimpleDateFormat("HH:mm:ss").format(parameter) : null);
    // builder.append('\'');
    // }
    builder.append('\'');
    builder.append((null != parameter) ? new SimpleDateFormat("HH:mm:ss").format(parameter) : null);
    builder.append('\'');
}
项目:openjdk-jdk10    文件:Bug4845901.java   
@SuppressWarnings("deprecation")
static void testParse(SimpleDateFormat sdf, String str, int expectedHour) {
    try {
        Date parsedDate = sdf.parse(str);
        if (parsedDate.getHours() != expectedHour) {
            throw new RuntimeException(
                    "parsed date has wrong hour: " + parsedDate.getHours()
                    + ", expected: " + expectedHour
                    + "\ngiven string: " + str
                    + "\nparsedDate = " + parsedDate);
        }
    } catch (java.text.ParseException e) {
        throw new RuntimeException("parse exception", e);
    }
}