I have 50000 XML records like this in the database:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<urlMD5>11ca7070ad6eb3180c53281e7b597976</urlMD5>
<date>
<year>2011</year>
<month>8</month>
<day>6</day>
<h>19</h>
<m>26</m>
<s>40</s>
</date>
<enc>utf-8</enc>
</root>
as you see, I saved the date in separated format.
Now I need to extract the currentTimeMillis() of these days and save to database in new field.
So I can easily compare them with current currentTimeMillis() and find out which document have been stored in last two days.
for example:
int ct = currentTimeMillis();
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/crawler?" + "user=root&password=&useUnicode=true&characterEncoding=UTF-8");
Statement stat = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM DBName WHERE ct - 60 * 60 * 24 * 2 > timeField");
And because I want to use this field for so many times, I want to use a simple query and I don't want to extract the XML format each time.
The problem is currentTimeMillis() function calculate currentTimeMillis that passed from January 1, 1970 and I need to calculate the same thing with my data.
I have written following code with the same code that I used before to store XML data to make sure if I can do it or not:
int s = 0;
s += (Calendar.getInstance().get(Calendar.YEAR) - 1970) * 60 * 60 * 24 * 365;
s += (Calendar.getInstance().get(Calendar.MONTH)) * 60 * 60 * 24 * 31;
s += (Calendar.getInstance().get(Calendar.DAY_OF_MONTH) * 60 * 60 * 24);
s += (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) * 60 * 60);
s += (Calendar.getInstance().get(Calendar.MINUTE) * 60);
s += (Calendar.getInstance().get(Calendar.SECOND));
System.out.println(s);
System.out.println(System.currentTimeMillis() / 1000);
but the results are not the same:
1312313680
1312643080
One of the reasons is because not every month have 31 days.
Any way, I need help to find out how can I calculate the currentTimeMillis with special date, not the current date?
I should mention that I am using mysql, so maybe I can save the dates in special format that I can compare the with SQL query?
Use the set method of Calendar:
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
etc.
And then extract the number of milliseconds with c.getTime().getTime().
Related
I have a java.util.Calendar variable (like 2016-05-24 00:01:05.780) and I want to get the total of seconds of the time. In this example, I want to get 65 as result.
I tried to use myCalendarVariable.getTimeInMillis()/1000 but I got -2208977011 as result.
How can I do that?
You can try
variable.get(Calendar.HOUR_OF_DAY) * 60 * 60 + variable.get(Calendar.MINUTE) * 60 + variable.get(Calendar.SECOND)
Note that Calendar.HOUR_OF_DAY is used when you're using a 24-hour clock, whereas Calendar.HOUR should be used for 12-hour clocks. In this situation you want to use the former.
Try to use get function:
myCalendarVariable.get(HOUR_OF_DAY)* 3600 + myCalendarVariable.get(MINUTE) * 60 + myCalendarVariable.get(SECOND)
Not sure which scope of seconds you were looking for, so try one of these:
Calendar myCalendarVariable = Calendar.getInstance();
int secondsInHour = myCalendarVariable.get((Calendar.MINUTE) * 60) + myCalendarVariable.get(Calendar.SECOND);
int secondsOfDay = (myCalendarVariable.get(Calendar.HOUR_OF_DAY) * 60 * 60) + secondsInHour;
You can try this:
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = minutes*60 + calendar.get(Calendar.SECOND);;
If you can convert your date into a LocalDateTime you can the seconds of day directly.
The convertion from Calendar to LocalDateTime has been omitted, as you might have the data in another format. This should be easy to amend to your needs.
LocalDateTime of = LocalDateTime.of(2016, 5, 24, 0, 1, 5, 780000000);
System.out.println("seconds of day: " + of.getLong(ChronoField.SECOND_OF_DAY));
output
seconds of day: 65
In my java (actually, Android, but it's irrelevant here) project, the user can enter start and end time for some activity and the system automatically computes the duration. On button press, I use System.currentTimeMillis() to get the current timestamp.
For reasons outside the scope of this question, I need to discard the date part of the timestamp and only store the time one. Easy, I thought, just divide by the number of milliseconds in a day and take the remainder:
long currentTimestamp = System.currentTimeMillis();
long timeOnly = currentTimeStamp % (1000 * 60 * 60 * 24);
This almost works - except it produces timestamp one hour off. Here's an example:
DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US);
long currentTimestamp = System.currentTimeMillis();
long timeOnly = currentTimestamp % (1000 * 60 * 60 * 24);
System.out.println("Full value: " + timeFormat.format(currentTimestamp));
System.out.println("Time only: " + timeFormat.format(timeOnly));
This code prints:
Full value: 10:53 PM
Time only: 11:53 PM
Full value: 11:19 PM
Time only: 12:19 AM
While I can just subtract one hour from the timestamp, I want to actually understand the reason why this is happening.
Try:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(System.currentTimeMillis()));
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.YEAR, 0);
calendar.set(Calendar.DAY_OF_MONTH, 0);
System.out.println("Full value: " + timeFormat.format(currentTimestamp));
System.out.println("Time only: " + timeFormat.format(calendar.getTimeInMillis()));
The Calendar instance will use your current Timezone and all setters will take the change the timezone into consideration. Thus, it should work.
Note:
The question remains, why you want to do that. Do you just want to store time information in a database, instead of having the 'full date' stored? If you want to do that, than you could map your current locale time to a UTC time (instead of using currentTimeMillis()).
I am trying to find the difference between two java dates with time zone.
Time zone is GMT.Sever sends the time in this format 2015-04-08 11:17:53 -0400. I want to find the difference (in minutes)between server sent date format and current android system time.
I am finding the difference like this.c_date is the server date format(2015-04-08 11:17:53 -0400)
public static long getDiffrenceBetween(String c_date,String old_date) {
System.out.println("Cuttent Time :::"+c_date);
System.out.println("Saved/Old Time :::"+old_date);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
Date d1 = null;
Date d2 = null;
long min_In_Minutes=0;
try {
d1 = format.parse(c_date);
d2 = format.parse(old_date);
// in milliseconds
long diff = d1.getTime() - d2.getTime();
min_In_Minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
System.out.println("Diff in Minutes :::"+min_In_Minutes);
long diffSeconds = diff / (1000 % 60);
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println(diffDays + " days, ");
System.out.println(diffHours + " hours, ");
System.out.println(diffMinutes + " minutes, ");
System.out.println(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
return min_In_Minutes;
}
but this is giving negative value in minutes. what is wrong in this method. Please suggest.
Hoping that can find a solution here.
Thanks in advance,
sharath.
As you are using Android you obiosly cant use Java 8 and its new time api so I would reccomand using Joda-time - an external library for time.
Example for between calculation:
Seconds.between(startDate, endDate);
More details here: joda
GMT is the time anywhere in the world. GMT time code shows the difference between GMT and your local time. So theoretically ,
if your local time code is +/- "GMT 5.00"
difference between GMT and your local time = 5 * 60 minutes
I have to calculate the difference between to dates, I have found a way but I have this strange result, Am I missing something?
public static void main(String[] args) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
long result = format.parse("2012-03-25 24:00").getTime() - format.parse("2012-03-25 00:00").getTime();
System.out.println("Difference in hours: " + result/(1000*60*60));
result = format.parse("2012-03-26 24:00").getTime() - format.parse("2012-03-26 00:00").getTime();
System.out.println("Difference in hours: " + result/(1000*60*60));
}
This is the result:
Difference in hours: 23
Difference in hours: 24
Thanks for the advices, now I'm using the Joda libray, I have this question, when I calculate the difference in this way:
DateTime begin = new DateTime("2012-03-25T00:00+01:00");
DateTime end = new DateTime("2012-03-26T00:00+01:00");
Hours m = Hours.hoursBetween(begin, end);
If I use this way to calculate the hours I get 24 hours (because the DST is not considered I assume)
What class/calculus should I use in order to get as result the 23 hours considering the DST (I have already tried different ways but I don't get it) the Period class?
Thanks for all the help...
Chances are you happen to have picked a date where daylight saving time changed in that time zone, so the day could really have been only 23 hours long. (March 25th 2012 certainly was the DST change date for Europe, e.g. Europe/London. We don't know what your default time zone is though.)
If you set your date format to use UTC, you shouldn't see this effect. (It's somewhat odd to use 24:00 in a string representation, mind you.) It's not clear what your data is meant to represent though, or what you're trying to measure. You should work out what time zone your data is really meant to be in, if you want to work out how much time actually elapsed between those local times.
(As noted in another answer, Joda Time is a much better API in general - but you still need to know how to use it properly, and when trying to work out the actual elapsed time, you'd still have seen the same results here.)
Must place the library file like explained below.
import java.util.Date;
String dateStart = dateChooserCombo1.getText();
String dateStop =dateChooserCombo2.getText();
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
//System.out.print(diffDays + " days, ");
jTextField3.setText(""+diffDays);
} catch (Exception e) {
e.printStackTrace();
}
I store a java.sql.Timestamp in a postgresql database as Timestamp data type and I want to find out the difference in minutes or hours from the one stored in the DB to the current timestamp. What is the best way about doing this? are there built in methods for it or do I have to convert it to long or something?
I ended using this, just want to post it for others if they search for it.
public static long compareTwoTimeStamps(java.sql.Timestamp currentTime, java.sql.Timestamp oldTime)
{
long milliseconds1 = oldTime.getTime();
long milliseconds2 = currentTime.getTime();
long diff = milliseconds2 - milliseconds1;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
return diffMinutes;
}
Use the UNIX_TIMESTAMP function to convert the DATETIME into the value in Hour, minutes and seconds.
And if you are not sure of which value is bigger then use the ABS function.
For date add/remove this is my generic function :
public static Date addRemoveAmountsFromDate(Date date, int field, int amount) {
Calendar tempCalendar = Calendar.getInstance();
tempCalendar.setTime(date);
tempCalendar.add(field, amount);
return tempCalendar.getTime();
}
example for "field" : Calendar.HOUR_OF_DAY, Calendar.MINUTE
Just use:
Date.compareTo(Date)
You have to convert java.sql.Timestamps to Date first.
date_part function can give you hours or as the interest may be but, it is a kind of substr and hence can't rely on it. You need to convert your timestamp value into unix_timestamp and extract total elapsed number of hours, minutes or whatever relevant since your timestamp till current_timestamp.
Example:
select age( now(), timestamp '2010-11-12 13:14:15' );
//results the interval to be "*1 year 6 mons 2 days 04:39:36.093*"
select date_part( 'hours', age( now(), timestamp '2010-03-10 02:03:04' ) );
// results *4* which is not correct.
Correct value of hours or others can be calculated after finding total number of seconds elapsed since 1970. This can be achieved using epoch with extract function.
epoch returns total number of seconds since 1970-01-01 00:00:00-00. And, you know, we can convert it into hours by dividing it with 3600.
Using epoch with extract:
select
EXTRACT( EPOCH FROM current_timestamp - timestamp '2010-11-12 13:14:15' ) as total_seconds,
EXTRACT( EPOCH FROM current_timestamp - timestamp '2010-11-12 13:14:15' ) / 3600 as total_hours;
ROUND(
EXTRACT( EPOCH FROM current_timestamp - timestamp '2010-11-12 13:14:15' ) / 3600
) as total_hours_rounded;
// results:
----------------+--------------+-----------------------
| total_seconds | total_hours | total_hours_rounded |
| --------------+--------------+----------------------|
| 47452282.218 | 13181.189505 | 13181 |
----------------+--------------+-----------------------
Similarly, we can extract other required values and use as required.
Use this, It is extremely accurate :
long diff = end - start;
long diffDays = diff / (24 * 60 * 60 * 1000);
long remain = diff % (24 * 60 * 60 * 1000);
long diffHours = remain / (60 * 60 * 1000);
remain = remain % (60 * 60 * 1000);
long diffMinutes = remain / (60 * 1000);
remain = remain % (60 * 1000);
long diffSeconds = remain / (1000);
System.out.println("days : " + diffDays);
System.out.println("hours : " + diffHours);
System.out.println("minutes : " + diffMinutes);
System.out.println("secs: " + diffSeconds2);
So the answer to this is pretty ancient and it came up when I was searching for an elegant solution.
There is a much nicer way to do this without having to faff with millisecond conversions:
long totalHours = ChronoUnit.HOURS.between(startTime.toInstant(), endTime.toInstant());
long totalMinutes = ChronoUnit.MINUTES.between(startTime.toInstant(), endTime.toInstant());
long totalSeconds = ChronoUnit.SECONDS.between(startTime.toInstant(), endTime.toInstant());
And a bunch of others MILLIS, YEARS, DAYS, HALF_DAYS, DECADES, CENTURIES and more!
Only thing I'm not sure about is if these longer units account for leap years and you may need to apply some changes if you want to account for time zones and DST.
Enjoy.