要使用Java中的SimpleDateFormat类,请导入以下包。
import java.text.SimpleDateFormat;
现在,使用SimpleDateFormat(“ ss”)设置格式,以两位数显示秒。
Format f = new SimpleDateFormat(”ss”);
现在,获取字符串中的秒数-
String strSeconds = f.format(new Date());
以下是一个例子-
import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Calendar; public class Demo { public static void main(String[] args) throws Exception { //显示当前日期和时间 Calendar cal = Calendar.getInstance(); SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s"); System.out.println("Today's date = "+simpleformat.format(cal.getTime())); //显示小时 Format f = new SimpleDateFormat("H"); String strHour = f.format(new Date()); System.out.println("Current Hour = "+strHour); //显示分钟 f = new SimpleDateFormat("mm"); String strMinute = f.format(new Date()); System.out.println("Current Minutes = "+strMinute); //以两位数显示秒 f = new SimpleDateFormat("ss"); String strSeconds = f.format(new Date()); System.out.println("Current Seconds = "+strSeconds); } }
输出结果
Today's date = 26/November/2018 08:06:42 Current Hour = 8 Current Minutes = 06 Current Seconds = 42