I searched topics about formatting time but these were all about Date class or DateTime. I am working with Time class. I created time as:
Time time = new Time(Time.getCurrentTimezone()) ;
time.setToNow();
String berkay = time.toString();
System.out.println(berkay);
When I execute it the output is :
20130417T070525GMT(3,106,0,0,1366182325)
actually date and time is correct (2013-04-17 07:05:25)
but I need to convert it into : 20130417070525 (My reason to do this is I will search database according to date so it is easier to compare times in that format)
How can I convert it?
Try this:
Time time = new Time(System.currentTimeMillis()) ;
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String date = df.format(time).toString();
System.out.println(date);
EDIT
But as smttsp suggested its much more efficient to store it as timestamp
To convert java.util.Date into String you should consider java.text.SimpleDateFormat.
For using java.util.Date as a parameter of a database query you should pass the Date as is without converting it into any other format.
passing Date parameter to create date range query
<- In the answer there is sample how to create such query.
It is a bit late but if you are working on time and you need to compare or sort, the best way is to use Unix timestamp. It starts from 1-Jan-1970 00:00:00 and increments 1 each second.
It is a long value(64 bit) which is quite efficient to use in both time and space. Here is the website for Unix timestamp conversion.
Also 20130417070525 is 14 char string(at least 15 byte, I guess) and 1366182325 is long(8 byte). So go for long value. U can get it in that way
Date myDate = new Date(); // current time
myDate.getTime(); // converts it to specified format.
Related
I needed to truncate milliseconds to seconds and implemented it in this way:
private static Long millisToSeconds(Long millisValue) {
return TimeUnit.MILLISECONDS.toSeconds(millisValue);
}
So now it truncates millis as expected, for example:
Long secondsValue = millisToSeconds(1554052265830L);
System.out.println("millisToSeconds ---> " + toSeconds);
// Prints millisToSeconds ---> 1554052265
But then I want to convert secondsValue to java.sql.Timestamp but the following implementation results in an error:
java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
What should I fix in my implementation to convert seconds to timestamp so that the resulting timestamp looks like 2019-03-31 11:45:06 ?
java.time
I am assuming that you are asking for a java.sql.Timestamp for use with your SQL database. In most cases you shouldn’t ask for that. The Timestamp class is poorly designed and long outdated, and a modern JDBC driver or JPA implementation will be happy to accept a type from java.time, the modern Java date and time API, instead.
long millisValue = 1_554_052_265_830L;
Instant i = Instant.ofEpochMilli(millisValue);
i = i.truncatedTo(ChronoUnit.SECONDS);
System.out.println(i);
2019-03-31T17:11:05Z
I don’t know why you wanted to truncate to seconds, but you can see that it has been done (or it’s easy to leave that line out).
Some JDBC drivers accept an Instant directly when you pass it to PreparedStatement.setObject (one of the overloaded versions of that method) even though the JDBC specification doesn’t require this. If yours doesn’t, use an OffsetDateTime instead. Convert like this:
OffsetDateTime odt = i.atOffset(ZoneOffset.UTC);
System.out.println(odt);
2019-03-31T17:11:05Z
You can see that the value is still the same, only the type is different.
What should I fix in my implementation to convert seconds to timestamp
so that the resulting timestamp looks like 2019-03-31 11:45:06 ?
First, as I said, you should fix your code not to require a Timestamp, but also you are asking the impossible. As far as I know, Timestamp.toString would always produce at least one decimal on the seconds, so it would at least look like 2019-03-31 11:45:06.0.
If you do indispensably need a Timestamp for a legacy API that you cannot or don’t want to change just now, convert the Instant from before:
Timestamp ts = Timestamp.from(i);
System.out.println(ts);
2019-03-31 19:11:05.0
Don’t be fooled by the time looking different (19:11 instead of 17:11). Timestamp prints in my local time zone, which is Europe/Copenhagen, 2 hours ahead of UTC since summer time (DST) began on March 31. So we have still got the same point in time.
Link: Oracle tutorial: Date Time explaining how to use java.time.
You can use SimpleDateFormatto format the date as per your requirement. See below
Long secondsValue = millisToSeconds(1554052265830L);
System.out.println("millisToSeconds ---> " + secondsValue);
Timestamp timeStamp = new Timestamp(secondsValue);
String formattedDate = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(timeStamp.getTime());
System.out.println(formattedDate);
The error suggest that you are using Timestamp.valueOf(String) (possibly with secondsValue.toString() as the argument?).
A java.sql.Timestamp is a special version of java.util.Date with nanosecond precision to serialize/deserialize SQL TIMESTAMP values. It is not a second value at all.
The constructor of Timestamp take a millisecond value, not a second value (for nanosecond precision, you need to use the separate setNanos with the sub-second nanoseconds).
In any case the proper way would be to use:
long milliseconds = ...;
long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds);
long truncatedMilliseconds = TimeUnit.SECONDS.toMillis(seconds);
// or truncatedMilliseconds = (milliseconds / 1000) * 1000;
Timestamp value = new Timestamp(truncatedMilliseconds);
However, since you are talking about needing a specific string format, I'm not sure you need this at all. Unless you are using JDBC to store this value in a database, you should not be using java.sql.Timestamp at all (and even when using JDBC, then it would probably be better to use java.time.LocalDatetime instead).
So, I was searching for this for some time but I didn't find an answer. Thats why I'm asking here. My problem goes like this:
With Swing I made an app that will get text from JTextArea and then save it inside a .txt document. Also it will save 2 more files (as .txt documents too). In one, there would be date (i.e 2016.03.05) and in other would be time (i.e 09:50 AM). What I need is compare the date and time to system date and time and check if they match. I only need a way on how to exactly do this, since they are stored as string, what would be good way to compare them to system date and time.
I think that is should be like this:
if(date in date file is equal to system date) {/do stuff}
I wouldn't rly be looking for spoonfeeding, but I need to have a good and efficient way of doing this.
Let's pretend the op has read the date/time strings from a file.
String date = "2016.03.05";
String time = "09:50 AM";
We want to compare that to the "system time" so how about.
LocalDateTime now = LocalDateTime.now();
Now we have a date and time and we want to compare it to the values in the file. One way, is to create a LocalDate object from the date string.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");
LocalDate localDate = LocalDate.parse(date, dateFormatter);
if(now.toLocaleDate().equals(localDate)){
//date is equal so now what?
}
We can do the same for the local time.
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:m a");
LocalTime localTime = LocalTime.parse(time, timeFormatter);
if(now.toLocalTime().equals(localTime)){
//do stuff if the time is equal (which it will rarely be)
}
If you are using java 8 then there is a very good article on how to parse a String to Date. Once you parse a String into class LocalDateTime then you can then run:
if(LocalDateTime.now().equals(yourTime)) {
//your code
}
to see if they match.
Please read about java.time package here https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html
and here is an article about String parsing to date: https://www.linkedin.com/pulse/java-8-javatime-package-parsing-any-string-date-michael-gantman?trk=pulse_spock-articles
It was discussed too many times, I know, but I can't get why the milliseconds generated by mine:
System.currentTimeMillis();
Or by:
Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis()
Are not equal to what I see on www.epochconverter.com?
What I need is to merely generate a String of concrete format, but I've found out the milliseconds aren't right.
Just in case here is how I do it:
private static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
public static String getCurrentTimestamp() {
long time = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
String lastModifiedTime = sdf.format(time);
Logger.logVerbose(TAG, "Generated timestamp is " + lastModifiedTime);
return lastModifiedTime;
}
What I finally get is just a local time, but I need the only time which is pure UTC without conjunction with my timezone.
I've even checked it with SQLite (using the SELECT strftime('%s',timestring);) and got the correct milliseconds. Why then I got it incorrectly generated by those two statements I posted above? Thanks a lot in advance.
Three things to consider
Java doesn't support UTC with leap seconds, only GMT. This is because OSes don't support it.
Your milli-seconds will be inaccurate unless you get the time off a satellite synchronized device.
You cannot run the command at exactly the same time so they will different some of the time.
But more importantly than that, if you don't set the tiemzone it will use the default time zone.
SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
// no time zone set so the default is used.
String lastModifiedTime = sdf.format(time);
Instead you should add
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Adding a 'Z' to the format will change the timezone no more than adding 'T' to the format, it is just a letter you added.
If you want the date format to format the time in the UTC zone, then use
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
I'd like to insert the value derived from this JXDatePicker into a Date field in Java DB. How should I get ONLY date off this controller in a way that time is represented as dd/mm/yyyy and nothing else??!
You can get the Date from the JXDatePicker.getDate() and then use a SimpleDateFormat to format the date into the required format.
Try:
SimpleDateFormat formater = new SimpleDateFormat("dd/MM/yyyy");
formater.format(myDatePicker.getDate());
Notice that instead of the mm that you've used I used MM to represent the month. Please see the SimpleDateFormat javadoc for pattern letters you can use.
Follow-Up
I feel compelled to mention, for completeness, that it is generally a bad idea to put formatted strings representing dates into a database; what happens when you want to display it in another format, for instance, or do a simple comparison using SQL.
One way to store date/times is to use the timestamp that you get from Date.getTime(). Here's the Date class' getTime() javadoc:
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
Storing this representation of a Date in your database makes it much simpler to create a Date object when you retrieve the timestamp:
Long myTimeStamp = getTimeStampFromResultSet();
Date date = new Date(myTimeStamp);
Or use the column in SQL to do a simple comparison:
SELECT * FROM MY_TABLE WHERE MY_DATE > ?
It also makes it somewhat portable so you can, for instance, send the timestamp to a thin client that is built using a different technology.
That being said, it is also in your best interest to use a date and time library like Joda Time instead of using the unreliable and inconvenient Java Date or Calendar classes.
i have a time stamp coming in my XML that i put into my database.
The time stamp is in the format of number of seconds gone by since 1970.
i want to convert that into a date object.
how do i go about it?
thank you in advance.
You can create a Date instance based on the number of milliseconds since Jan 1, 1970. Your value is expressed in seconds, but that a trivial conversion:
long timestamp = getTimestampInSeconds(); // some megic to get the value
Date date = new Date(timestamp * 1000); // convert to milliseconds
Date class has special constructor for this:
Date result = new Date(numberOfSec * 1000);
Further you can format your Date object as you like using SimpleDateFormat.
See the doc.
It's been awhile since the question been asked, but i just faced the same trouble.
And I found out that the trouble is in the variable type. Are you using integer to store the timestamp value? Try using long. It worked for me