Increment Time by one second in a loop - java

Here is a simple test: I am trying to increment current timestamp by 1 second in a loop. The output is not what I expect.
public class TimeTest {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
for (int i = 0; i < 10; i++) {
cal.add(Calendar.SECOND, i);
System.out.println("Updated = " + cal.getTime());
}
}
}
Instead of neat 1 second increments, I get increments from anywhere between 5 seconds to 1 second.
Updated = Mon May 13 15:12:45 PDT 2013
Updated = Mon May 13 15:12:46 PDT 2013
Updated = Mon May 13 15:12:48 PDT 2013
Updated = Mon May 13 15:12:51 PDT 2013
Updated = Mon May 13 15:12:55 PDT 2013
Updated = Mon May 13 15:13:00 PDT 2013
Updated = Mon May 13 15:13:06 PDT 2013
Updated = Mon May 13 15:13:13 PDT 2013
Updated = Mon May 13 15:13:21 PDT 2013
Updated = Mon May 13 15:13:30 PDT 2013

You want to add 1 instead of i on each for loop iteration.
cal.add(Calendar.SECOND, 1);

cal.add(Calendar.SECOND, 1);
Simply increment the calendar by 1 second instead of i seconds

Related

How do i get a particular day from Jan to Dec

I am new to java and I am trying to get all the 7th day in the year 2009.
I am a bit confused about how to go about it. Below is my code
public class Main {
public static void main(String[] args) {
System.out.println("WELCOME TO MY CALENDER CLASS");
Calendar calendar = Calendar.getInstance();
calendar.set(DAY_OF_MONTH,7);
calendar.set(Calendar.YEAR,2009);
for(int i =1; i <= 12; i++){
calendar.set(DAY_OF_MONTH,i);
System.out.println(calendar.getTime());
}
}
}
Update: This below is my result
Sun Mar 01 23:41:14 GMT 2009
Mon Mar 02 23:41:14 GMT 2009
Tue Mar 03 23:41:14 GMT 2009
Wed Mar 04 23:41:14 GMT 2009
Thu Mar 05 23:41:14 GMT 2009
Fri Mar 06 23:41:14 GMT 2009
Sat Mar 07 23:41:14 GMT 2009
Sun Mar 08 23:41:14 GMT 2009
Mon Mar 09 23:41:14 GMT 2009
Tue Mar 10 23:41:14 GMT 2009
Wed Mar 11 23:41:14 GMT 2009
Thu Mar 12 23:41:14 GMT 2009
OK, assuming you are starting from 1st of January here is a simple example for your cause. I hope Java1.8 code is clear to you.
public static void main(String[] args) {
// create two localdate start of a year instances, one for current year and one for next year, 2009 and 2010 respectively
LocalDate thisYear = LocalDate.of(2009, Month.JANUARY, 1);
LocalDate nextYear = LocalDate.of(2010, Month.JANUARY, 1);
// used only for counting number of every seventh day in a year
int i=0;
// while we are not in the next year, 2010
while (thisYear.isBefore(nextYear)) {
i++;
// print current date
System.out.println(i+" " + thisYear.toString());
// add a week or seven days to our thisYear instance and loop thru again
thisYear = thisYear.plusWeeks(1);
}
}
The problem with your code is that in the for loop you set the day and not the month for the Calendar object.
So change to this:
for(int i = 0; i < 12; i++){
calendar.set(Calendar.MONTH, i);
System.out.println(calendar.getTime());
}
The loop starts from 0 and goes up to 11 because the months are 0 based.
If you can use LocalDate then your code would be much simpler and more efficient:
System.out.println("WELCOME TO MY CALENDER CLASS");
LocalDate date;
for(int i = 1; i <= 12; i++){
date = LocalDate.of(2009, Month.of(i), 7);
System.out.println(date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
}

Loop in csv file

I asked this question before however I did not get the answer that I expected. Therefore I opened this new question.
My try:
String fileName = "placements.csv";
try {
// Assume default encoding.
FileWriter fileWriter = new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
// First row, write the head of the csv file.
bufferedWriter.write(FILE_HEADER);
bufferedWriter.newLine();
// Increase the begin date 1 seconds until test end date.
int seconds = 0;
Calendar cal = Calendar.getInstance();
cal.setTime(beginDate);
for (int j = 0; j < convertedDifference; j++) {
for (Job currentJob : NEHCalculator.sequenceOrderListofJobs()) {
int times = (int) ((convertedDifference / currentJob.getInterval()) * testDevices());
for (int i = 0; i < currentJob.getNeededTestTime() * times; i++) {
cal.add(Calendar.SECOND, 1);
beginDate.getTime();
// write the test date
bufferedWriter.write(String.valueOf(cal.getTime()));
bufferedWriter.write(";");
bufferedWriter.write(String.valueOf(seconds));
bufferedWriter.write(";");
bufferedWriter.write(currentJob.getJobname());
bufferedWriter.write(";");
bufferedWriter.newLine();
}// end of currentjob loop
seconds++;
}// end first for loop
}
bufferedWriter.close();// Always close files.
} catch (IOException ex) {
System.out.println("Error writing to file '" + fileName);
}
}
First for loop for (int j = 0; j < convertedDifference; j++) : I restrict my program until test end date. If I enter 1 hour test time, i expected to see number 0 until 3599 seconds.
Second for loop for (Job currentJob : NEHCalculator.sequenceOrderListofJobs()): I want to test every devices in the list.
For third for loop for (int i = 0; i < currentJob.getNeededTestTime() * times; i++): I expected to test first job currentJob.getNeededTestTime() * times times.
For example I have 1 hour test time and interval of fist job is 15 min and it tests 2 devices and test needed time 2 seconds. So the output must be:
Mon Feb 22 12:59:59 CET 2016;0;WAF5-H;
Mon Feb 22 13:00:00 CET 2016;1;WAF5-H;
Mon Feb 22 13:00:01 CET 2016;2;WAF5-H;
Mon Feb 22 13:00:02 CET 2016;3;WAF5-H;
Mon Feb 22 13:00:03 CET 2016;4;WAF5-H;
Mon Feb 22 13:00:04 CET 2016;5;WAF5-H;
Mon Feb 22 13:00:05 CET 2016;6;WAF5-H;
Mon Feb 22 13:00:06 CET 2016;7;WAF5-H;
Mon Feb 22 13:00:07 CET 2016;8;WAF5-H;
Mon Feb 22 13:00:08 CET 2016;9;WAF5-H;
Mon Feb 22 13:00:09 CET 2016;10;WAF5-H;
Mon Feb 22 13:00:10 CET 2016;11;WAF5-H;
Mon Feb 22 13:00:11 CET 2016;12;WAF5-H;
Mon Feb 22 13:00:12 CET 2016;13;WAF5-H;
Mon Feb 22 13:00:13 CET 2016;14;WAF5-H;
Mon Feb 22 13:00:14 CET 2016;15;WAF5-H; then it will continue with second job until end of the job list.
However the output of my code is:
Mon Feb 22 12:59:59 CET 2016;0;WAF5-H;
Mon Feb 22 13:00:00 CET 2016;0;WAF5-H;
Mon Feb 22 13:00:01 CET 2016;0;WAF5-H;
Mon Feb 22 13:00:02 CET 2016;0;WAF5-H;
Mon Feb 22 13:00:03 CET 2016;0;WAF5-H;
Mon Feb 22 13:00:04 CET 2016;2;WAF5-H;
Mon Feb 22 13:00:05 CET 2016;2;WAF5-H;
Mon Feb 22 13:00:06 CET 2016;2;WAF5-H;
Mon Feb 22 13:00:07 CET 2016;2;WAF5-H;
Mon Feb 22 13:00:08 CET 2016;2;WAF5-H; until Mon Feb 22 17:55:08 CET 2016;7082;WAF5-H;
It is completely wrong and I spend really so soo much time but I failed with this task. Could someone please help me.
Best regards,
What about changing this code
bufferedWriter.write(String.valueOf(seconds));
for this one:
bufferedWriter.write(String.valueOf(cal.get(Calendar.SECOND)));
I think it might work

How do I get my "Date" object to print out different values each time I call it?

I have been asked to add println statements throughout an existing project so that the dates/times of each process can be printed out as they execute.
The first thing I should mention is that I have to stick to Java 7 due to project constraints. I am aware that Java 8 has a nice little LocalDateTime.now() function to make determining the current date and time a hell of a lot easier, shame we can't use it.
Anyway. I've written a mini project to test this functionality before I build it into the existing code.
I have a class CreateDate that allows me to create a new Date object and print out the current date/time as follows:
package datetest;
import java.util.Date;
public class CreateDate {
public void returnDate() {
Date date = new Date();
System.out.println("The current date and time is: " + date);
}
}
I have another class, Printer, that creates an instance of CreateDate and calls the returnDate method as follows:
package datetest;
public class Printer {
public static void main(String[] args) {
CreateDate date = new CreateDate();
date.returnDate();
}
}
However, no matter how many times I try to print out the current date/time, the date object is initialised with the same date and time, every time. I'm looking to print out different dates to specify the current time that something is being executed.
Please help! I'm relatively new to Java, so any advice you could offer would be much appreciated.
You have to "save" the object in some field - you are creating new Date object every time you call returnDate method, so:
public class CreateDate {
protected Date date;
public CreateDate() {
this.date = new Date();
}
public void returnDate() {
System.out.println("The current date and time is: " + this.date);
}
}
I think you're over complicating this. The following program prints a different date each time it is run:
import java.util.Date;
public class Main {
public static void main(String[] args) {
System.out.println("The current time is "+new Date());
}
}
If you want it factored out, then:
import java.util.Date;
public class Printer {
static public void printCurrentTime() {
System.out.println("The current time is " + new Date());
}
}
With:
public class Main {
public static void main(String[] args) throws Exception {
for( int i = 0; i< 10; i++) {
Printer.printCurrentTime();
Thread.sleep(10000);
}
}
}
This program produces
The current time is Wed Oct 14 11:10:40 BST 2015
The current time is Wed Oct 14 11:10:50 BST 2015
The current time is Wed Oct 14 11:11:00 BST 2015
The current time is Wed Oct 14 11:11:10 BST 2015
The current time is Wed Oct 14 11:11:20 BST 2015
The current time is Wed Oct 14 11:11:30 BST 2015
The current time is Wed Oct 14 11:11:40 BST 2015
The current time is Wed Oct 14 11:11:50 BST 2015
The current time is Wed Oct 14 11:12:00 BST 2015
The current time is Wed Oct 14 11:12:10 BST 2015
import java.util.Date;
public class MyDate {
private Date date;
#Override
public String toString() {
date = new Date();
return date.toString();
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public static void main(String[] args) throws InterruptedException {
MyDate currentDate = new MyDate();
for(int i = 0; i < 100; i++) {
Thread.sleep(100);
System.out.println(currentDate);
}
}
}
produces
Wed Oct 14 16:14:19 IST 2015
Wed Oct 14 16:14:20 IST 2015
Wed Oct 14 16:14:20 IST 2015
Wed Oct 14 16:14:20 IST 2015
Wed Oct 14 16:14:20 IST 2015
Wed Oct 14 16:14:20 IST 2015
Wed Oct 14 16:14:20 IST 2015
Wed Oct 14 16:14:20 IST 2015
Wed Oct 14 16:14:20 IST 2015
Wed Oct 14 16:14:20 IST 2015
Wed Oct 14 16:14:20 IST 2015
Wed Oct 14 16:14:21 IST 2015
Wed Oct 14 16:14:21 IST 2015
Wed Oct 14 16:14:21 IST 2015
Wed Oct 14 16:14:21 IST 2015
Wed Oct 14 16:14:21 IST 2015
Wed Oct 14 16:14:21 IST 2015
Wed Oct 14 16:14:21 IST 2015
Wed Oct 14 16:14:21 IST 2015
Wed Oct 14 16:14:21 IST 2015

Quartz cron schedule output not as expected

I want to schedule a daily job at 23:59:59 only in weekdays (monday - friday).
i use this cron expression
"59 59 23 ? * MON-FRI",
but the output has tripe value for monday
Wed Aug 29 23:59:59 ICT 2012
Thu Aug 30 23:59:59 ICT 2012
Fri Aug 31 23:59:59 ICT 2012
Mon Sep 03 23:59:59 ICT 2012
Mon Sep 03 23:59:59 ICT 2012
Mon Sep 03 23:59:59 ICT 2012
Tue Sep 04 23:59:59 ICT 2012
Wed Sep 05 23:59:59 ICT 2012
Thu Sep 06 23:59:59 ICT 2012
Fri Sep 07 23:59:59 ICT 2012
is the expression wrong? need help.
i'm getting this output by loop through specific date, here the code
`try {
CronExpression ce = new CronExpression(59 59 23 ? * MON-FRI);
Calendar start = Calendar.getInstance();
start.setTime(new Date());
Calendar end = Calendar.getInstance();
Date endDate = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse("Fri Sep 29 23:59:59 ICT 2012");
end.setTime(endDate);
for (; !start.after(endDate); start.add(Calendar.DATE, 1)) {
Date current = start.getTime();
System.out.println(ce.getNextValidTimeAfter(current));
}
} catch (ParseException ex) {
Logger.getLogger(HelloJob.class.getName()).log(Level.SEVERE, null, ex);
}
}`
The problem isn't in you rule or in Quartz, it's OK and you may use it.
The problem is in your test code.
for (; !start.after(endDate); start.add(Calendar.DATE, 1)) {
Date current = start.getTime();
System.out.println(ce.getNextValidTimeAfter(current));
}
You're not iterating on valid dates but on all days between startDate and endDate.
The loop content is called for invalid days too and for each of those 2 invalid days the "next valid time" after current date is monday. So you have thrice monday, that's perfectly logic.
Hence your log.

Next dates using java

How can I calculate next dates using Java?
For example, if the user gives me the current date in a field like 2011-02-21, then I want to give back the same day of the month for the next two months: 2011-03-21, 2011-04-21.
Using Joda-Time:
DateTime dt = new DateTime(2005, 3, 26, 0, 0, 0, 0);
Period everyMonth= Period.months(1);
DateTime dt1 = dt.plus(everyMonth);
DateTime dt2 = dt1.plus(everyMonth);
DateTime dt3 = dt2.plus(everyMonth);
DateTime dt4 = dt3.plus(everyMonth);
DateTime dt5 = dt4.plus(everyMonth);
System.out.println(dt.toDate());
System.out.println(dt1.toDate());
System.out.println(dt2.toDate());
System.out.println(dt3.toDate());
System.out.println(dt4.toDate());
System.out.println(dt5.toDate());
OUTPUT
Sat Mar 26 00:00:00 CST 2005
Tue Apr 26 00:00:00 CDT 2005
Thu May 26 00:00:00 CDT 2005
Sun Jun 26 00:00:00 CDT 2005
Tue Jul 26 00:00:00 CDT 2005
Fri Aug 26 00:00:00 CDT 2005
How about using DateTime of YodaTime?
new DateTime().plusDays(nDays)?
See also plusMonths()
Use Calendar.add(...)
Here is the example:
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 31);
c.set(Calendar.MONTH, Calendar.DECEMBER);
System.out.println(c.getTime());
c.add(Calendar.DAY_OF_YEAR, 1);
System.out.println(c.getTime());
This prints:
Sat Dec 31 21:25:12 IST 2011
Sun Jan 01 21:25:12 IST 2012
(I just wanted to check that this really gives correct result when the next date is in the next year.)
Using Calendar like #AlexR said, you can use the add(...) method to add a point in the date.
This:
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 21);
c.set(Calendar.MONTH, Calendar.FEBRUARY);
System.out.println("user entered date:");
System.out.println(c.getTime());
System.out.println();
System.out.println("next five months:");
for (int i = 0; i < 5; i++) {
c.add(Calendar.MONTH, 1);
System.out.println(c.getTime());
}
Prints out:
user entered date:
Mon Feb 21 15:56:49 EST 2011
next five months:
Mon Mar 21 15:56:49 EDT 2011
Thu Apr 21 15:56:49 EDT 2011
Sat May 21 15:56:49 EDT 2011
Tue Jun 21 15:56:49 EDT 2011
Thu Jul 21 15:56:49 EDT 2011
Take a look at the Java Calendar, in particular the method add.
http://answers.yahoo.com/question/index?qid=20080613024301AAm7KbP

Categories

Resources