我试图查看如何在显示Array项时更改DateToStr
(Unix时间)。当前,它总是显示同一时间。
public class Testarray {
public static void main(String args[]) {
SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String DateToStr = format.format(new Date());
String[] anArray = {
"001,"+ DateToStr +",,F,", "001,"+ DateToStr +",,F,", "001,"+ DateToStr +",,F,"
};
for (int i =0 ;i <anArray.length;i++) {
try{
// show array element every 10sc with new date and time.
Thread.sleep(10000);
}catch(InterruptedException ex){
}
System.out.println(anArray[i]);
}
}
当前输出:
001,181102074606,,F,
001,181102074606,,F,
001,181102074606,,F,
预期的输出:每个输出应该有新的日期,因为它要延迟10秒。
答案 0 :(得分:3)
DateToStr变量对于数组中的所有三个条目都是通用的,这就是为什么它每次都给您相同的日期。如果希望您的日期每次都是新的,则必须在睡眠方法之前的循环中获取该值。
尝试一下
SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String[] anArray = new String[3];
char c ='E';
for (int i =0 ;i <anArray.length;i++) {
try{
anArray[i]= "001,"+ format.format(new Date()) +",,"+c+",";
c++;
// show array element every 10sc with new date and time.
Thread.sleep(10000);
}catch(InterruptedException ex){
}
System.out.println(anArray[i]);
}
答案 1 :(得分:0)
每次插入时,您需要更新DateToStr
值。
然后您一次插入所有内容。您只能以10秒的延迟阅读。
正确的做法是在两次插入之间等待10秒,并在每次插入时读取日期。
SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String[] anArray = new String[3];
for(int i = 0; i < anArray.length; ++i) {
try {
// Sleep before inserting
Thread.sleep(1000);
// Insert with new value every time
anArray[i] = "001,"+ format.format(new Date()) + ",,F,";
System.out.println(anArray[i]);
} catch (InterruptedException ex) {
}
}