要求打印格式类似于:[\"2:00am\",\"2:01am\",\"2:02am\",\"2:03am\",\"2:04am\",\"2:05am\",\"2:06am\"......]
我用线程目前能取到00:01AM 开始的数据,代码如下
- Java code
import java.text.SimpleDateFormat;import java.util.Date;public class TimeGain implements Runnable { Date nDate = null ; public void run() { int i = 0; while (i < 24) { i++; System.out.println(i);// 此处处理逻辑// try {// //获取时间// SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");// Date date = new Date();// date.setHours(0);// date.setMinutes(0);// Hashtable<String,Date> temp = new Hashtable<String,Date>();// // // System.out.println(sdf.format(date));// if(date.getHours()<12){// System.out.println(sdf.format(date)+"am");// }else{// System.out.println(sdf.format(date)+"pm");// }// Thread.sleep(60000);// } catch (Exception e) {// e.printStackTrace();// } SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); try { Date initDate = getInitDate(); initDate.setMinutes(initDate.getMinutes()+1); if(initDate.getHours()<12){ System.out.println(sdf.format(initDate)+"am"); }else{ System.out.println(sdf.format(initDate)+"pm"); } Thread.sleep(60000); } catch (InterruptedException e) { e.printStackTrace(); } } } public Date getInitDate(){ if(nDate == null){ nDate = new Date(); nDate.setHours(0); nDate.setMinutes(0); } return nDate; } public static void main(String[] args) { TimeGain tt = new TimeGain(); Thread t = new Thread(tt); t.start(); }}
输出结果如下:
00:01am
00:02am
00:03am
00:04am
00:05am
00:06am
00:07am
00:08am
00:09am
00:10am
00:11am
问题一:我的数据只能取到00:24AM 应该在哪进行修改
问题二:如何取到要求格式的输出形式
麻烦请在附上代码 感谢
------解决方案--------------------
你都用线程控制时间每分钟执行一次了,就不要每次都取时间了,自己累加就可以了
- Java code
public class TimeGain implements Runnable { public void run() { int hh = 0; int mm = 0; while (hh < 24) { try { System.out.printf("\"%02d:%02d%s\",", hh, mm, (hh < 12 ? "am" : "pm")); mm++; if (mm == 60) { mm = 0; hh++; } if (hh == 24) {break;} Thread.sleep(60000); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { TimeGain tt = new TimeGain(); Thread t = new Thread(tt); t.start(); }}
------解决方案--------------------
我的建议用定时器做也可以
- Java code
import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class Test { static int h = 0; static int m = 0; public static void main(String[] args) throws Exception { TimerTask task = new TimerTask() { @Override public void run() { // 调用业务方法 System.out.printf("\"%02d:%02d%s\",", h, m, (h < 12 ? "am" : "pm"));//复制阿宝的,嘿嘿,学习了! m++; if (m == 60) { m = 0; h++; } if (h == 12) h = 0; } }; // 创建一个定时器 Timer timer = new Timer(); // 设值 3 秒钟后开始执行第一次,以后每隔 1 秒中执行一次 // timer.schedule(task, 3 * 1000, 1 * 1000); // 设值现在开始执行第一次,以后每隔 60 秒中执行一次 timer.schedule(task, new Date(), 60 * 1000); }}