Date different

  • Thread starter News-proxy.phk.philips.com
  • Start date
N

News-proxy.phk.philips.com

I want write a program delete old files. Need to change the modified date .
How to Calculate Date diff ?
ldatediff = Now - (long) files.lastModified() ?


import java.io.*;
import java.util.*;
//import java.util.Date;
import java.text.*;

public class Dir_t {
static int indentLevel = - 1;

TimeZone zone = new SimpleTimeZone(8*60*60*1000,"GMT+0800");
Calendar cal = Calendar.getInstance(zone);// this seems to be a point
Date currdate = new Date();

Dir_t (String path) {
listPath (new File (path));
}




void listPath (File path) {
File files []; //List of files in a Directory
indentLevel++; // Going Down...
String datestr;
int k;
long ldatediff ;

// Create list of files in this dir
files = path.listFiles();

// Sort with help of Collections API
Arrays.sort(files);
for (int i= 0, n=files.length ; i < n ; i++) {
for (int indent = 0 ; indent < indentLevel; indent++) {
System.out.print(" ");
}

cal.set(Calendar.YEAR, 1970); // example


DateFormat formatter = new SimpleDateFormat();
formatter.setCalendar(cal); //this is necessary

Date date = new Date(files.lastModified());
formatter.format(date);
cal.add(cal.DATE,0); /* Date Offset */


datestr = cal.get(cal.YEAR) +"/";
k = cal.get(cal.MONTH) + 1;


if ( k <= 9 )
datestr = datestr + "0" + k + "/";
else
datestr = datestr + k + "/";

if (cal.get(cal.DATE) < 10 )
datestr = datestr + "0" + cal.get(cal.DATE);
else
datestr = datestr + cal.get(cal.DATE);

// Calculate Date diff
ldatediff = (long) files.lastModified() ;


// System.out.println(files.toString() + ", "
// + (new Date (files.lastModified())) );


System.out.println( datestr + " " + ldatediff + " " +
files.toString()) ;

if (files.isDirectory()) {

listPath(files);
}
}
indentLevel--; // and going up
}
public static void main (String args[]) {
new Dir_t(args[0]);

}
}
 
A

Andrew

Roedy said:
There are many different ways to define difference. See
http://mindprod.com/jgloss/calendar.html
for the code.
i'm new to Java, i've heard how good it is but to be honest for all the
good things it drops the ball on simple things like date manipulation.

for instance, I want to pass a date/time to a query, the date and time
to use are strings (dd/mm/yy hh:mm.ss), to get it from strings to the
accepted format is nothing but nuts, i've tried so many options but
nothing seems to work. I dont care about TZ, locales etc I just want the
value to use in the query.

Can anyone help me please.
 
A

Andrew Thompson

Andrew said:
i'm new to Java, i've heard how good it is but to be honest for all the
good things it drops the ball on simple things like date manipulation.

Name the language(s) that doesn't.
for instance, I want to pass a date/time to a query, the date and time
to use are strings (dd/mm/yy hh:mm.ss), to get it from strings to the
accepted format is nothing but nuts, i've tried so many options but
nothing seems to work. I dont care about TZ, locales etc ..

Don't you?

Q: How many hours are there between 6pm, 30 september 2005,
and 6am, 1 October 2005?

A: It depends. If the *locale* in question changes
to/from daylight saving time at midnight, it will be
either 11 hours or 13 hour - else 12 hours.

<zen answer>
Manipulating dates is hard in any language
(unless the language does a very poor job of it).
</zen answer>
 
A

Andrew

Andrew said:
Name the language(s) that doesn't.



Don't you?

Not at all, all I need is to write the date and time. When the report is
written the actual date and time is reported. In my case, there is
absolutely no need to confuse the operator with daylight savings or TZ.
Q: How many hours are there between 6pm, 30 september 2005,
and 6am, 1 October 2005?

I agree that if I want to do this like you suggested then thats fine but
when the KISS method is applied, Date misses the mark.

In this app I will never need to work out time differences like this.
Only simple date time recording is required.
A: It depends. If the *locale* in question changes
to/from daylight saving time at midnight, it will be
either 11 hours or 13 hour - else 12 hours.

Either the action took place at that time or not. Once again I have no
need to calulate differences.
 
S

Stefan Ram

Andrew Thompson said:
Manipulating dates is hard in any language

I recently have developed my own API for this, which does not
use any standard classes of Java for dates and time, except to
get the current locale.

The class "de.dclj.ram.system.gregorian.Point" models a time
point and can handle conversion between a double value giving
the offset to the epoch and a broken-down time.

The class "de.dclj.ram.notation.iso8601.Point" can convert
to/from a subnotation of ISO 8601 date notation.

The class "de.dclj.ram.input.time.Point" can set objects
implementing a "clock"-interface to the current time.

Here are some examples of usage of these classes.

/* get the current time ... */
final de.dclj.ram.system.gregorian.Point now =
new de.dclj.ram.system.gregorian.Point();
de.dclj.ram.input.time.Point.setToNow( now );

/* ... and print it */
java.lang.System.err.println
( new de.dclj.ram.notation.iso8601.Point( now ) );
/* 2005-10-04T12:50:30+00:00 */

/* get the current time with the locale time zone ... */
final de.dclj.ram.system.gregorian.Point now1 =
new de.dclj.ram.system.gregorian.Point();
de.dclj.ram.input.time.Point.setToWallClock( now1 );

/* ... and print it */
java.lang.System.err.println
( new de.dclj.ram.notation.iso8601.Point( now1 ));
/* 2005-10-04T14:50:30+02:00 */

/* change the time zone, but not the time point */
java.lang.System.err.println
( new de.dclj.ram.notation.iso8601.Point( now1 ).shiftTo( "-06:00" ) );
/* 2005-10-04T06:50:30-06:00 */

/* get the offset to the epoch in days */
java.lang.System.err.println
( new de.dclj.ram.notation.iso8601.Point( "1970-01-01T00:00:00+00:00" ).doubleValue() );
/* 719163.0 */
/* The epoch used is the proleptic gregorian date 1-1-1T00:00:00+00:00 */

/* get difference between two dates in days */
java.lang.System.err.println
( new de.dclj.ram.notation.iso8601.Point( "2005-09-08T00:17:05+02:00" ).doubleValue() -
new de.dclj.ram.notation.iso8601.Point( "1950-04-02T14:30:02+02:00" ).doubleValue() );
/* 20247.407673611073 */

/* get difference between two dates with different time zones */
java.lang.System.err.println
( new de.dclj.ram.notation.iso8601.Point( "2005-09-08T00:17:05+00:00" ).doubleValue() -
new de.dclj.ram.notation.iso8601.Point( "2005-09-08T00:17:05+02:00" ).doubleValue() );
/* 0.08333333337213844 */

/* add days to a date */
de.dclj.ram.notation.iso8601.Point point =
new de.dclj.ram.notation.iso8601.Point( "1950-04-02T14:30:02+02:00" );
final de.dclj.ram.system.gregorian.Point gregorian = point.getGregorian();
gregorian.add( 12345.67890123 );
java.lang.System.err.println
( new de.dclj.ram.notation.iso8601.Point( gregorian ));
/* 1984-01-20T06:47:39+02:00 */

/* change the timezone, leave the time point */
java.lang.System.err.println
( new de.dclj.ram.notation.iso8601.Point( "1950-04-02T14:30:02+02:00" ).shiftTo( "+00:00" ));
/* 1950-04-02T12:30:02+00:00 */

Some of the above methods might throw a java.text.ParseException.

I plan to release the code under the GPL, but it still needs
to be straightened up. This was done as a subproject of my
chores-manager.
 
L

Lasse Reichstein Nielsen

Andrew said:
for instance, I want to pass a date/time to a query, the date and time
to use are strings (dd/mm/yy hh:mm.ss), to get it from strings to the
accepted format is nothing but nuts, i've tried so many options but
nothing seems to work. I dont care about TZ, locales etc I just want
the value to use in the query.

Will this do?
---
public static Date stringToDate(String dateString) throws ParseException {
DateFormat format = new SimpleDateFormat("dd/MM/yy HH:mm.ss");
Date date = format.parse(dateString);
return date;
}
 
S

steve

i'm new to Java, i've heard how good it is but to be honest for all the
good things it drops the ball on simple things like date manipulation.

for instance, I want to pass a date/time to a query, the date and time
to use are strings (dd/mm/yy hh:mm.ss), to get it from strings to the
accepted format is nothing but nuts, i've tried so many options but
nothing seems to work. I dont care about TZ, locales etc I just want the
value to use in the query.

Can anyone help me please.

post us the sql query so we can see.
steve
 
A

Andrew

steve said:
post us the sql query so we can see.
steve
hi steve,

i've done a workaround to get it happening, as I don't need locales etc
I just set everything to UTC and have written a few methods (using
SimpleDateFormat & DateFormat) to do the massaging.

thanks
 
P

P.Hill

Roedy said:
Date is the lemon of Java. There is a complicated replacement called
Calendar.

As others sometimes try to tell Roedy; Calendar is not a replacement for
Date. Calendar is the place all those really messy algorithms go, date
is the token that holds what in many DB contexts is referred to as a
timeStamp.

-Paul
 
P

P.Hill

Andrew said:
for instance, I want to pass a date/time to a query, the date and time
to use are strings (dd/mm/yy hh:mm.ss), to get it from strings to the
accepted format is nothing but nuts,

Solution one: learn PreparedStatements, so you can do things like:

myPS.set(5, new Date());

which will set the 5th parameter to the moment right now and do ANY
appropriate conversion.
or use
myPS.set('CreationDate', new Date());

Solution two: if you insist on creating your own SQL
(which I would NOT recommend, because Prep. Statements have other
advantages) then use something along the lines of:

Date myDate = new Date();
SimpleDateFormat sdf =
new SimpleDateFormat("dd/MM/yy HH:mm.ss");
String myDateString = sdf.format( myDate );
System.out.println( myDateString );

Notice that for the simple case, there is NO need to be making your own
Calendar nor timezone when creating todays datetime right now where you
are (but do make sure your system is running with a proper timezone
otherwise any software including a Java VM won't work with the right times.

*****

Need to convert a datetime, a (binary) java.util.Date,
to view or use it as a String in a different timezone than the one
your machine is set to? Okay, then and only then you should start
thinking about timezones.

Date myDate = new Date();
SimpleDateFormat sdf =
new SimpleDateFormat("dd/MM/yy HH:mm.ss zzz (ZZZ)");
System.out.println(sdf.format(myDate));

// Set the TZ appropriately
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(sdf.format(myDate));

For example I just got:
04/10/05 22:27.02 PDT (-0700)
05/10/05 01:27.02 EDT (-0400)

It's the same moment in time, DISPLAYED in different timezones.

See Roedy's site at http://mindprod.com/jgloss/timezone.html
for a convenient list of TZs.

****

Want to make up a date from some numeric fields? That's
when you use a Calendar.

SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm.ss zzz
(ZZZ)");
Calendar c = new GregorianCalendar();
c.set(0,0,0,0,0,0); // don't forget to clear all fields
c.set(2002, Calendar.JULY, 16); // a handy method
System.out.println(sdf2.format(c.getTime()));
c.set( Calendar.YEAR, 2088);
System.out.println(sdf2.format(c.getTime()));
c.set( Calendar.MONTH, Calendar.SEPTEMBER); // use the symbols!
System.out.println(sdf2.format(c.getTime()));
c.set( Calendar.DAY_OF_MONTH, 10);
System.out.println(sdf2.format(c.getTime()));
c.set( Calendar.HOUR, 11);
System.out.println(sdf2.format(c.getTime()));
c.set( Calendar.MINUTE, 12);
System.out.println(sdf2.format(c.getTime()));
c.set( Calendar.SECOND, 13);
System.out.println(sdf2.format(c.getTime()));

results in:

2002-07-16 00:00.00 PDT (-0700)
2088-07-16 00:00.00 PDT (-0700)
2088-09-16 00:00.00 PDT (-0700)
2088-09-10 00:00.00 PDT (-0700)
2088-09-10 11:00.00 PDT (-0700)
2088-09-10 11:12.00 PDT (-0700)
2088-09-10 11:12.13 PDT (-0700)

Now that wasn't so hard was it?
Okay, the API IS more than a bit clunky, but it does
contain some useful parts.

There is also sdf.parse() which can be put to good use.

Contact me if you need to do other Date calculations/conversions.
-Paul
 
S

steve

Solution one: learn PreparedStatements, so you can do things like:

myPS.set(5, new Date());

which will set the 5th parameter to the moment right now and do ANY
appropriate conversion.
or use
myPS.set('CreationDate', new Date());

Solution two: if you insist on creating your own SQL
(which I would NOT recommend, because Prep. Statements have other
advantages) then use something along the lines of:

Date myDate = new Date();
SimpleDateFormat sdf =
new SimpleDateFormat("dd/MM/yy HH:mm.ss");
String myDateString = sdf.format( myDate );
System.out.println( myDateString );

Notice that for the simple case, there is NO need to be making your own
Calendar nor timezone when creating todays datetime right now where you
are (but do make sure your system is running with a proper timezone
otherwise any software including a Java VM won't work with the right times.

*****

Need to convert a datetime, a (binary) java.util.Date,
to view or use it as a String in a different timezone than the one
your machine is set to? Okay, then and only then you should start
thinking about timezones.

Date myDate = new Date();
SimpleDateFormat sdf =
new SimpleDateFormat("dd/MM/yy HH:mm.ss zzz (ZZZ)");
System.out.println(sdf.format(myDate));

// Set the TZ appropriately
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(sdf.format(myDate));

For example I just got:
04/10/05 22:27.02 PDT (-0700)
05/10/05 01:27.02 EDT (-0400)

It's the same moment in time, DISPLAYED in different timezones.

See Roedy's site at http://mindprod.com/jgloss/timezone.html
for a convenient list of TZs.

****

Want to make up a date from some numeric fields? That's
when you use a Calendar.

SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm.ss zzz
(ZZZ)");
Calendar c = new GregorianCalendar();
c.set(0,0,0,0,0,0); // don't forget to clear all fields
c.set(2002, Calendar.JULY, 16); // a handy method
System.out.println(sdf2.format(c.getTime()));
c.set( Calendar.YEAR, 2088);
System.out.println(sdf2.format(c.getTime()));
c.set( Calendar.MONTH, Calendar.SEPTEMBER); // use the symbols!
System.out.println(sdf2.format(c.getTime()));
c.set( Calendar.DAY_OF_MONTH, 10);
System.out.println(sdf2.format(c.getTime()));
c.set( Calendar.HOUR, 11);
System.out.println(sdf2.format(c.getTime()));
c.set( Calendar.MINUTE, 12);
System.out.println(sdf2.format(c.getTime()));
c.set( Calendar.SECOND, 13);
System.out.println(sdf2.format(c.getTime()));

results in:

2002-07-16 00:00.00 PDT (-0700)
2088-07-16 00:00.00 PDT (-0700)
2088-09-16 00:00.00 PDT (-0700)
2088-09-10 00:00.00 PDT (-0700)
2088-09-10 11:00.00 PDT (-0700)
2088-09-10 11:12.00 PDT (-0700)
2088-09-10 11:12.13 PDT (-0700)

Now that wasn't so hard was it?
Okay, the API IS more than a bit clunky, but it does
contain some useful parts.

There is also sdf.parse() which can be put to good use.

Contact me if you need to do other Date calculations/conversions.
-Paul


using
connection.setdate(int,date())
connection.getdate(int)

ties your code too much to the table format, one change to your database ,
and it's broken, or consider a table with 70 or greater columns, where you
have to setup 70 lines each to deal with a different field, then you want
to add 1 in the middle.


the most effective way i have found is to copy the data to an object [],
then have another object[] holding the metadata column type for the row.

whenever accessing a date field, do it via getters & setters methods.
but the biggest problem , is say getting 50 records containing dates from a
database to display in a Jtable , but not wanting the second/microsecond
component.
 
P

P.Hill

steve said:
using
connection.setdate(int,date())
connection.getdate(int)

ties your code too much to the table format, one change to your database ,
and it's broken, or consider a table with 70 or greater columns, where you
have to setup 70 lines each to deal with a different field, then you want
to add 1 in the middle.

All good points, I was dwelling on the Date problems, so didn't go
into the advantages of either PreparedStatement using the column
name or copying to Business/middle-tier data structures.
whenever accessing a date field, do it via getters & setters methods.
but the biggest problem , is say getting 50 records containing dates from a
database to display in a Jtable , but not wanting the second/microsecond
component.

It could either be your JTables job to override the cell renderer
which would then use a a SimpleDateFormat to generate an appropriate
String (without milliseconds) given a Date, or it may be your
middle-tier object that converts any random date, datetime, timestamp
etc from the database into some other appropriate business object.

For a key to what a MyDateHandlingJTable might need to do see:
http://www.devx.com/tips/Tip/15851

-Paul
 
R

Roedy Green

As others sometimes try to tell Roedy; Calendar is not a replacement for
Date. Calendar is the place all those really messy algorithms go, date
is the token that holds what in many DB contexts is referred to as a
timeStamp.

Calendar is a replacement in the sense many of Date's methods have
been deprecated or duplicated in function in Calendar.

Date should have been dropped entirely and replaced with Long or long
or something with no methods or fields other than a long since that is
all it really is now. It's name was and still is wrong. It is not a
date. It is a date/timestamp.
 
R

Roedy Green

As others sometimes try to tell Roedy; Calendar is not a replacement for
Date.

Just because I am not persuaded by your arguments does not necessarily
mean I did not read or understand them.

Obviously, Calendar is not a complete replacement for Date. It is too
fat. It is designed for doing date calculation, not just transporting
a date/time as an object which is the new function of Date.

I find your patronising unusually inappropriate. I'm the guy who
documented the Date gotchas and presented it at the Colorado Software
confererence where I helped persuade Sun they needed a replacement..
I'm the guy who wrote BigDate, a Date replacement which does the
calendar calculations for satellite communication networks. I'm the
guy who introduced Calendar to the world with an article in Java
Developer's Journal.
 
S

steve

All good points, I was dwelling on the Date problems, so didn't go
into the advantages of either PreparedStatement using the column
name or copying to Business/middle-tier data structures.


It could either be your JTables job to override the cell renderer
which would then use a a SimpleDateFormat to generate an appropriate
String (without milliseconds) given a Date, or it may be your
middle-tier object that converts any random date, datetime, timestamp
etc from the database into some other appropriate business object.

For a key to what a MyDateHandlingJTable might need to do see:
http://www.devx.com/tips/Tip/15851

-Paul

i tracked it down!!
oracle changed the default types returned for their newest oracle drivers, so
getobject() actually returns the WRONG type.
you now have to SPECIFICALLY get the data with 'rset.getTimestamp', which now
means the code has to compare the metadata for every column.


it's not pretty now it's something like this!!

while (rset.next()) {
for (int i = 0; i < record1.length; i++) {
//warning this may have changed from type 91 to
93
if (recordStruc.ourrecTypePointer() ==
TIMESTAMPMETADATAVALUE) {
java.sql.Timestamp FinalTimestamp =
(java.sql.Timestamp)new TIMESTAMP().timestampValue();
Timestamp TimestampFromDatabase =
rset.getTimestamp(1 + i);
if (TimestampFromDatabase != null) {
FinalTimestamp = TimestampFromDatabase;
//allocate existing date
}
else {
//do nothing because we already have an
empty timestamp!!
// DummyTimestamp =
(java.sql.Timestamp)new TIMESTAMP().timestampValue();
}
record1 = FinalTimestamp;
}
else {
record1 = rset.getObject(1 + i);
// COPY THE DATA TO A LOCAL ARRAY OF
THE RIGHT SIZE
}
}
 
S

steve

Just because I am not persuaded by your arguments does not necessarily
mean I did not read or understand them.

Obviously, Calendar is not a complete replacement for Date. It is too
fat. It is designed for doing date calculation, not just transporting
a date/time as an object which is the new function of Date.

I find your patronising unusually inappropriate. I'm the guy who
documented the Date gotchas and presented it at the Colorado Software
confererence where I helped persuade Sun they needed a replacement..
I'm the guy who wrote BigDate, a Date replacement which does the
calendar calculations for satellite communication networks. I'm the
guy who introduced Calendar to the world with an article in Java
Developer's Journal.

Just let it go roedy it does not matter.

The problem is that the latest oracle driver says that the "type"
returned by the metadata is different from the actual data returned.
so for oracle at least , you can no longer just get an array of objects, you
now have to check the metadata , before reading the data from the rset.

Steve
 
R

Roedy Green

i tracked it down!!
oracle changed the default types returned for their newest oracle drivers, so
getobject() actually returns the WRONG type.

I thought JDBC was supposed to bypass that nonsense.
 
P

P.Hill

steve said:
I said:
It could either be your JTables job to override the cell renderer
which would then use a a SimpleDateFormat to generate an appropriate
String (without milliseconds) given a Date, or it may be your
middle-tier object that converts any random date, datetime, timestamp
etc from the database into some other appropriate business object.
[...]

i tracked it down!!
oracle changed the default types returned for their newest oracle drivers, so
getobject() actually returns the WRONG type.
you now have to SPECIFICALLY get the data with 'rset.getTimestamp', which now
means the code has to compare the metadata for every column.

At 1st blush that seems like a violation of the ResultSet API contract.
What is the inheritance tree of this new object which it would
give you by default if you load up for an array of objects?

-Paul
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top