how do i create a custom date? - java

need some help! this is sort of a 2 part question..
ive done a decent amount of programming but ive never really worked with dates, ive googled and all that but finding nothing.
part 1:
so lets say i have some variable:
Public Date adStartTime
i want it to be in this format: yyyy/mm/dd hh:mm:ss
so i just do adStartTime = (some date formatter) + (2011/08/08 08:08:08) *which dont work
whats the proper way to get it to be that way?? i keep getting errors and such.. id prefer to do everything in Date instead of using strings/int..
part 2:
once i get the date in that format i will need to insert that into db, can i insert the date in that format? or will i need to change it?
reason i will need the time is because i am setting up automated ads for new company securities and sometimes the ad will run for one day or maybe 1/2 day so i will need to set the timer correctly.
thanks for any help..

For part 1, use a java.text.SimpleDateFormat, like so:
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(datestring);
If you have code that looks anything like this, and still get errors, please edit your question to include your actual code.
For part 2, you should insert the date in the database as a Date, not as a String, so there is no format.

1.) For working with dates I suggest you look at Joda time
which allows exactly that type of conversion .
for example
public boolean isAfterPayDay(DateTime datetime) {
if (datetime.getMonthOfYear() == 2) { // February is month 2!!
return datetime.getDayOfMonth() > 26;
}
return datetime.getDayOfMonth() > 28;
}
2.) for storing dateTimes in a DB there are several camps which hold different things
Some say you should store an int and convert . Joda makes that easy . Others ( like some oracle DBAs) seem to prefer a Date type. Joda handles that as well. There is a discussion of some of the issues here Date storage discussion
How you actually do it can depend on your database type and the preferences of your DBA ( if you have one )
I would strongly suggest that you store datetime with a storage of Timezone .

Related

Best strategy to persist ISO8601

I have been reading different articles on the said question yet i am unable to figure out what should be the best strategy to store the date in db.
I will be receiving the ISO8601 date via path-param in a rest call. What I have decided
Use Joda-Time to parse the date.
Extract UTC-0 time out of the date and the hours offset
Store UTC-0 in DateTime datatype in mysql db and store offset in varchar(5).
When I have to search something based on the date (an exposed rest api). I will use the search criteria (input date) extract the UTC-0 time and hours offset and compare the two columns in the db i.e. where table.dateInUTC0 = :inputDateInUTC0 AND table.hoursOffset = :inputHoursOffset
I am not sure about step 4. Am i doing i right ?
I am not sure about step 4. Am i doing i right ?
Really, it depends on what you are trying to do.
If you want the search to only match if the searcher is using the same timezone as the original data, then you are doing it right.
If you don't want that, you are doing it wrong.
Ask yourself this: If you enter the same date / time in your local time zone and UTC (or some other time zone), do they mean the same thing for clients of your server? Should they?

HSQLDB: Insert/Get Date with java

I'm using a HSQLDB to make a small program (with JavaFX gui) and I'm currently trying to get the "reservation" part to work (the user can add new ones or search for existing ones in a restricted period of time).
For that I already added a few dates beforehand (I'm using a database.sql script), e.g.:
INSERT INTO reservations(begin, end) VALUES ('2013-08-01', '2013-08-31')
I already wrote a few methods (create, update, delete, search, findAll) and now I'm kind of stuck on the "create" part.
I want to insert new reservations into the DB with
pstmt = con.prepareStatement("INSERT INTO reservations(begin, end) VALUES (?,?)");
but I'm having problems creating new Dates that I can insert.
pstmt.setDate(1, (java.sql.Date) beg);
Doesn't work (I'm using java.util.Date objects to save the exported dates from the DB), it just aborts my tests (jUnit).
Calendar cal1 = Calendar.getInstance();
cal1.set(2014, 0, 1);
Date beginn = cal1.getTime();
only creates dates in the form of: Wed Jan 01 12:23:15 CET 2014
But (and I don't know how exactly dates are saved in HSQLDB) I want the date to be "YYYY-MM-DD".
So, what's the best way of converting the calendar dates into the format I need (and caste them? Unfortunately, casting a String to Date doesn't work). And: Is my approach of using java.util.Date dates okay if I'm going to use JavaFX to let the user select a starting and an end date?
Instead of (java.sql.Date) beg causing a ClassCastException you should write:
new java.sql.Date(beg.getTime()); // provided beg is of type java.util.Date as you wrote
If you use strings in VALUES-clause you might consider JDBC-escape-syntax for dates. And your statement "only creates dates in the form of: Wed Jan 01 12:23:15 CET 2014" does not matter at all because you only see the output of method toString()of java.util.Date. It is not relevant for the internal state or storage in db. Your wish "I want the date to be "YYYY-MM-DD"." is rather relevant for representation layer of your application, not for the internal storage format of db which you have no control about other than choosing the appropriate db column type (here: ANSI-SQL-DATE).
In the representation layer you can use classes like SimpleDateFormatwith pattern "yyyy-MM-dd" for the output you wish.
EDIT (because of questions in comments):
Okay, you really don't need to worry about the toString()-representation of a java.util.Date-timestamp. Its internal state is only a long representing the elapsed millis since 1970-01-01 not counting leap seconds. Just ignore the standard output of java.util.Date which rather displays the system zone context but not so much the internal state. Using a.before(b) is quite okay and has nothing to do with the weird output of toString()-method of java.util.Date.
Furthermore: You have no real control about how your database tool displays the date column values. That is the secret of the tool you use. The internal state inside db might be quite different so every db is like a kind of black box.
But when you read the date values from db and present the data to the user then and exactly then you have to worry about the representation of the java.util.Date-objects. For this purpose I have recommended to use SimpleDateFormat - see above. But this adaptation (conversion to readable human date format) is not in db-tool, not in the JDBC-layer, but only in user-representation layer, normally in UI.

How to store and retrieve milliseconds in a date object in Java?

I'm making a basic Java program that reads in a subtitle (.srt) file and I would like to store each time as a Date object. I really only need to keep track of Hours, minutes, seconds, and milliseconds (to 3 digits). I think I am able to store it using this:
String start = "00:01:01,604";
DateFormat sdf = new SimpleDateFormat("hh:mm:ss,SSS");
Date startDate = sdf.parse(start);
For retrieving, I can do something like this:
return String.format("\nStart: %d:%d:%dText: %s\n", startDate.getHours(),startDate.getMinutes(), startDate.getSeconds(), text);
I'm looking for something that would do something similar to getMilliseconds (if it existed). Thank you very much!
What you're handling is not a date! Don't use the Date class to handle it! Dates have strange extra rules that you don't care about and that could easily trip you up (just think of leap years, leap seconds and time zones).
You should either
use a long to hold the milliseconds and handle the calculation on your own (it's not so hard, you're not implementing a calendar) or
use an existing duration class such as the one from Joda Time.
The recommended way to get access to part of date (hours,minutes, etc.) in Java is now using Calendar.get(Calendar.MILISECONDS), see javadocs. In case of your code it would look like this:
Date startDate = sdf.parse(start);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
int milliseconds = calendar.get(Calendar.MILISECONDS);
P.S. Please note that regarding to javadocs Date.getHours(),Date.getSeconds(), etc. methods are currently deprecated anyway. Don't use them :).
Just call date.getTime() and get milliseconds.
You can always use Date.getTime() for getting value in milliseconds. It will return a value in long format

Add a date to now by parsing the input

I'm having an hard time trying to parse date in the future, and I would apreciate some help!
Here's the thing, I'd like to add a parsed date to the current date (to have it in the future). The problem is that I can have many kind of date format, like :
dd
MM-dd
yyyy-MM-dd
So if the user set something like 5, the returned date will be (in our timelapse) 2011-11-05.
If he set 02-14, it will be 2012-02-14.
But suppose we are the 4th of november, and the user set 11-03, it will be 2012-11-03 and not 2011-11-03 since it's past.
I tried to play with Calendar, Date, SimpleFormat, but I cannot make it work.
My parsers (using SimpleDateFormat) are working though.
Could you help me archieve this? I'm not asking for a complete code, just something that would set me on the right track!
thanks! :)
Since you have fixed list of acceptable input date format, set the lenient field of dateFormat to false and check to see if one of them satisfy your work done or if exception is raised go for next pattern
dateFormat = new SimpleDateFormat(PATTERN_ONE);
dateFOrmat.setLenient(false);
dateFormat.parse(INPUT_STRING);
// if an exception is caughtm try with next pattern
I have had very good experience with jodatime - http://joda-time.sourceforge.net/. Checkout the Dateformatters in that.
It has a very extensive API and lets you do things like add and subtract dates - taking into account timezones and daylight saving etc.

Java and MySQL date problem

I do a
rs.getTimestamp("datetime")
in Java.
In the database, this datetime is 2009/03/06 02:47:18
but the time is returned as 14:47:18
I'm not very knowledgeable about MySQL dates, so I would appreciate any explanation as to why this is happening.
It doesn't matter. Its not about MySQL or any database. This is the format Timestamp shows up by default, I believe. It doesn't mean it missed the date or something.
You can always format the Timestamp returned by the method in any format in your code. Check out java.text.SimpleDateFormat class. Or for better, check out much more sophisticated Joda Time.
Two things. First, I think we need sample code. What's going on is not at all clear from what you've given us. Context, usage, DB schema, and sample rows as well.
Second, ResultSet.getTimestamp() should be returning an object of type Timestamp, rather than a String of any sort.
SimpleDateFormat time = new SimpleDateFormat("HHmmss");
datime = time.format(rs.getTimestamp("datetime"))
and then datime is printed to a file.
the datetime column in the table is a datetime Data Type

Categories