Java Code Examples for java.text.SimpleDateFormat

The following are top voted examples for showing how to use java.text.SimpleDateFormat. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: CalendarRegression.java   View source code 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example 2
Project: dubbox-hystrix   File: Envs.java   View source code 6 votes vote down vote up
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);
}
 
Example 3
Project: jobManage   File: UtilHelper.java   View source code 6 votes vote down vote up
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));
  }
 
Example 4
Project: urule   File: WriteJsonServletHandler.java   View source code 6 votes vote down vote up
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();
	}
}
 
Example 5
Project: atsd-web-test   File: AdminServiceTest.java   View source code 6 votes vote down vote up
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;
}
 
Example 6
Project: hands-on-api-proxy   File: PhotoDetailFragment.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 7
Project: MyCourses   File: KonsolRandevuUygulamasi.java   View source code 6 votes vote down vote up
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----");
	    }
		
	}
}
 
Example 8
Project: openNaEF   File: ConfigUtil.java   View source code 6 votes vote down vote up
@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;
}
 
Example 9
Project: PI-Web-API-Client-Java-Android   File: ApiClient.java   View source code 6 votes vote down vote up
/**
 * 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"));
    }
}
 
Example 10
Project: joanne   File: Sorter.java   View source code 6 votes vote down vote up
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());
    });
}
 
Example 11
Project: OpenDA   File: WflowBmiBridgeTest.java   View source code 6 votes vote down vote up
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());
}
 
Example 12
Project: openjdk-jdk10   File: DateFormatProviderImpl.java   View source code 6 votes vote down vote up
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;
}
 
Example 13
Project: parabuild-ci   File: IntervalCategoryLabelGeneratorTests.java   View source code 6 votes vote down vote up
/**
 * 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));
    
}
 
Example 14
Project: participants1b   File: DatabaseLoader.java   View source code 6 votes vote down vote up
@PostConstruct
 private void initDatabase() throws ParseException {
	
	Ciudadano c1 = new Ciudadano("Ramon", "Sobrino Llorca", "[email protected]",
			new SimpleDateFormat("yyyy-MM-dd").parse("1990-02-02"), "Oviedo", "Española", "71664900", "123456");
	Ciudadano c2 = new Ciudadano("Pablo", "Garcia", "[email protected]gmail.es",
			new SimpleDateFormat("yyyy-MM-dd").parse("1995-10-31"), "Oviedo", "Española", "79845632", "111111");
	Ciudadano c3 = new Ciudadano("Javier", "Fernandez", "[email protected]",
			new SimpleDateFormat("yyyy-MM-dd").parse("1992-02-02"), "Oviedo", "Española", "78945612", "999999");
	Ciudadano c4 = new Ciudadano("Benjy", "Rojas", "[email protected]",
			new SimpleDateFormat("yyyy-MM-dd").parse("1993-02-02"), "Oviedo", "Española", "78945612", "222222");
	repository.save(c1);
	repository.save(c2);
	repository.save(c3);
	repository.save(c4);
}
 
Example 15
Project: EosCommander   File: EosChainInfo.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 16
Project: Matisse   File: MediaStoreCompat.java   View source code 6 votes vote down vote up
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;
}
 
Example 17
Project: Sanxing   File: MyDuration.java   View source code 6 votes vote down vote up
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;
}
 
Example 18
Project: neoscada   File: XAxisDynamicRenderer.java   View source code 6 votes vote down vote up
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 );
    }
}
 
Example 19
Project: iBase4J   File: TypeParseUtil.java   View source code 6 votes vote down vote up
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));
	}
}
 
Example 20
Project: Automekanik   File: TeDhenat.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 21
Project: MKAPP   File: AdapterDns.java   View source code 5 votes vote down vote up
@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));
}
 
Example 22
Project: PaoMovie   File: ImageUtils.java   View source code 5 votes vote down vote up
/**
 * 生成输出文件路径
 *
 * @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;
}
 
Example 23
Project: asura   File: JmxServer.java   View source code 5 votes vote down vote up
/**
 * 
 * 启动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);
	}
}
 
Example 24
Project: uavstack   File: DateTimeHelper.java   View source code 5 votes vote down vote up
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;
    }
 
Example 25
Project: spline   File: FileBindingAdapters.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 26
Project: tulingchat   File: DateUtil.java   View source code 5 votes vote down vote up
/**
 * 两个时间之间的时间集合 格式自定义
 */
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;
}
 
Example 27
Project: Equella   File: Utils.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 28
Project: parabuild-ci   File: AbstractCommandBasedSourceControl.java   View source code 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 29
Project: minsx-authorization-server   File: MailUtil.java   View source code 5 votes vote down vote up
public Boolean sendMail(String to, String username, String title, String content) {
    Boolean isSuccess = true;
    Map<String, Object> params = new HashMap<>();
    params.put("headerLogo", "https://image.minsx.com/pic/minsx/logo/LogoOfWhite.png");
    params.put("footerLogo", "https://image.minsx.com/pic/minsx/logo/logoSuperGray.png");
    params.put("webSite", "https://www.minsx.com/");
    params.put("webName", "米斯云平台");
    params.put("welcome", String.format("尊敬的%s:", username));

    params.put("content", content);
    params.put("company", "米斯云平台");
    params.put("remind", "该邮件由米斯云平台系统发出,请勿直接回复!");
    params.put("copyRight", "如果您有任何问题,请及时联系我们:\nEmail: [email protected]\nCopyright © 2016-2017 minsx.com All rights reserved.");
    params.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    try {
        mailSender.sendSysTemplateMail(to, title, params);
    } catch (Exception e) {
        e.printStackTrace();
        isSuccess = false;
    }
    return isSuccess;
}
 
Example 30
Project: oldmonk   File: ReporterAPI.java   View source code 5 votes vote down vote up
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;
}
 
Example 31
Project: storj_hoststats_app   File: StorjNodeDetailActivity.java   View source code 5 votes vote down vote up
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";
    }
}
 
Example 32
Project: ClouldReader   File: TimeUtil.java   View source code 5 votes vote down vote up
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);
}
 
Example 33
Project: rongyunDemo   File: DateUtils.java   View source code 5 votes vote down vote up
/**
 * 得到当前时间
 * @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;
}
 
Example 34
Project: OpenJSharp   File: DerOutputStream.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 35
Project: Backmemed   File: FileManager.java   View source code 5 votes vote down vote up
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.");
	}
}
 
Example 36
Project: jetfuel   File: DateAdapter.java   View source code 5 votes vote down vote up
/**
 * 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);

}
 
Example 37
Project: GitHub   File: GoldPresenter.java   View source code 5 votes vote down vote up
@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);
                    }
                }
            })
    );
}
 
Example 38
Project: yyox   File: DateUtils.java   View source code 5 votes vote down vote up
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;
}
 
Example 39
Project: tangyuan2   File: TimeOnlyTypeHandler.java   View source code 5 votes vote down vote up
@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('\'');
}
 
Example 40
Project: openjdk-jdk10   File: Bug4845901.java   View source code 5 votes vote down vote up
@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);
    }
}