Count up timer in java not starting from 0 - java

I created a count up timer function to use in a java swing window. The problem is time does not start counting from zero. When I start the timer, the initial time always comes with an hour ahead.
Here's my code:
public static void timeRecording(){
Date startTime = new Date();
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss");
Date actualTime = new Date();
String dateToPrint = timeFormat.format(new Date(actualTime.getTime() - startTime.getTime()));
//String dateToPrint = timeFormat.format(actualTime);
System.out.println(actualTime);
//actualTime
// String timeToPrint.timeFormat = actualTime;
timerLabel.setText(dateToPrint);
}
};
new Timer(delay, taskPerformer).start();
}
This is the time shown at start:

Your SimpleDateFormat of "hh:mm:ss" uses h which, in the JavaDoc is described as:
h Hour in am/pm (1-12)
Thus your hour will always start at 1.
You could try using
K Hour in am/pm (0-11)
i.e. "KK:mm:ss"

What happens is that if the difference between the dates is one second, this: new Date(actualTime.getTime() - startTime.getTime()) creates a date at 1st of Jan 1970 at 00:01 UTC.
But when you format it, the DateFormat uses your time zone (Lisbon = UTC+1) and sees the date as 1st of Jan 1970 at 01:01 UTC+1.
If you want to get the correct output, you need to set the timezone of the formatter:
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(fmt.format(new Date(0))); //outputs 00:00:00 as expected
Note: The correct format pattern is HH (0-23), not hh (which is 1-12).

Related

Convert Hours and Minutes into Milliseconds and return into HH:mm:ss Format

Using TimeUnit I wanted to Convert Hours and Minutes into Milliseconds with the below code:
int hours = 01, minutes = 0;
long milliseconds = TimeUnit.SECONDS.toMillis(TimeUnit.HOURS.toSeconds(hours) + TimeUnit.MINUTES.toSeconds(minutes));
Works Fine with 3600000 milliseconds
And using SimpleDateFormat to return into HH:mm:ss format:
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date date = new Date(milliseconds);
String returnFormat = formatter.format(date); //Final Result.
and this give me a result of 09:59:59 which is not the expected output.
I am confused, what's wrong with the code above? I am expecting 01:00:00 output.
UPDATE:
Actually I am using the above code to create a simple countdown timer using Handler post.delayed function.
...
#Override
public void run() {
milliseconds -= 1000; //Remove 1 Seconds
handler.postDelayed(this,1000); //Delay in 1 Seconds
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); //Create Time Formatting
Date date = new Date(milliseconds); //Put the milliseconds into Format
String returnFormat = formatter.format(date));
Log.w("COUNTDOWN", returnFormat);
}
This happens because of your timezone is different. By making the timezone GMT you will be able to gain the expected result. Use the following code snippet.
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date date = new Date(milliseconds);
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
String returnFormat = formatter.format(date); //Final Result.
System.out.println(returnFormat);

Unique values of date

I am writing in a CSV and my calendar is doubling values ... I couldn't figure out the problem.
PS: Amount is like 1.000.000 or 10.000.000.
public static void CSV(String path, int amount) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.set(1980, 01, 01);
for (; set.size() < amount;) {
c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + 2);
set.add(c.getTime());
}
Iterator<Date> it = set.iterator();
for (int i = 0; i < amount; i++) {
csvWriter.append(dateFormat.format(it.next()));
}
...
}
Well, the error was the Hour in am/pm (1-12).
Thanks to #Teemu.
I assume you mean "doubling values" by that the same time occurs twice. Reason for that is your date formatter:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
You are formatting hours as 'hh'. Meaning that it is formatting date as Hour in am/pm (1-12) . So two time values are actually unique, one is AM and another is PM. You are not providing the AM / PM markings into SimpleDateFormat and that's why both time values looks the same.
If you want to distinquish the AM / PM markings change the format to this:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aaa");
Or another way is to format hours in 0-23 format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Not sure if my assumption is correct but I hope this helps.

How do I display current timezone and full datetime in two different TextView?

I want to display timezone as
Current Timezone is: Indian Standard Time (IST) (GMT +05:30)
and datetime as
Wednesday, 18-March-2015, 09:07:12 pm
and time 2nd TextView (datetime) should be updating every second.
I am creating date time as
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR);
int min = c.get(Calendar.MINUTE);
int sec = c.get(Calendar.SECOND);
and timezone as
TimeZone tz = TimeZone.getDefault();
current_Time_Zone = (TimeZone.getTimeZone(tz.getID()).getDisplayName(false, TimeZone.SHORT));
currentTimeZone.setText("Current Timezone: " + current_Time_Zone);
The textcreation itself shouldn't be a problem. For the update: use a Timer like this:
Timer t = new Timer(true);
t.schedule(new TimerTask() {
#Override
public void run() {
updateTime();
}
}, new Date() , 1000l);
This will update the Time every second, starting from the timercreation.

Check is new day/midnight java android

I have timer witch is triggered periodically every 30 minutes - how to check on each trigger is current time midnight (is it new day) ?
I tried something like this
SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
Date currTime = parser.parse( parser.format( date ) );
but I am not sure how to check if it is midnight, because I don't know does it use 24:00:00 or 00:00:00 for midnight clock, so I can use it and then check if current time is between midnight and lets say midnight and one minute like this :
if( currTime.after(midnight) && currTime.before(midnight and one minute) ){...}
You may want to try :
Calendar c = Calendar.getInstance();
int hours = c.get(Calendar.HOUR_OF_DAY);
int minutes = c.get(Calendar.MINUTE);
int seconds = c.get(Calendar.SECOND);
if(hours*3600 + minutes*60 + seconds < 1800){
// Day changed since last task
}

Date to string is not correnct

Probably there will be simply and fast answer but I still cant find out why is the result of
Date date = new Date(60000); //one min.
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String dateStr = dateFormat.format(date);
dateStr - 01:01:00
Still one hour more. Time zone? How can I set it without it? Thanks.
Date represents a specific moment in time, not a duration. new Date(60000) does not create "one minute". See the docs for that constructor:
Initializes this Date instance using the specified millisecond value. The value is the number of milliseconds since Jan. 1, 1970 GMT.
If you want "one minute from now" you'll probably want to use the Calendar class instead, specifically the add method.
Update:
DateUtils has some useful methods that you might find useful. If you want the elapsed time in HH:mm:ss format, you might try DateUtils.formatElapsedTime. Something like:
String dateStr = DateUtils.formatElapsedTime(60);
Note that the 60 is in seconds.
Three ways to use java.util.Date to specify one minute:
1. Using SimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")) as shahtapa said:
Date date = new Date(60*1000); //one min.
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
2. Using java.util.Calendar as kabuko said:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.MINUTE,1); //one min.
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
Other calendar.set() statements can also be used:
calendar.set(Calendar.MILLISECOND,60*1000); //one min.
calendar.set(1970,0,1,0,1,0); //one min.
3. Using these setTimeZone and Calendar ideas and forcing Calendar to
UTC Time-Zone
as Simon Nickerson said:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(Calendar.MINUTE,1); //one min.
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
Note: I had a similar issue: Date 1970-01-01 was in my case -3 600 000 milliseconds (1 hour late) java.util.Date(70,0,1).getTime() -> -3600000
I recommend to use TimeUnit
"A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units. A TimeUnit does not maintain time information, but only helps organize and use time representations that may be maintained separately across various contexts. A nanosecond is defined as one thousandth of a microsecond, a microsecond as one thousandth of a millisecond, a millisecond as one thousandth of a second, a minute as sixty seconds, an hour as sixty minutes, and a day as twenty four hours."
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/TimeUnit.html
Date date = new Date(); // getting actual date
date = new Date (d.getTime() + TimeUnit.MINUTES.toMillis(1)); // adding one minute to the date

Categories

Resources