I am using Java 6, and I have a time from the current date as a string, like this: 14:21:16, and I need to convert this to a Timestamp object to store in a database.
However there seems to be no good way to get a Timestamp from this. Timestamp.valueOf(String) is quite close, but requires a date. Is there a good way to make a Timestamp object from such a string?
How about this:
final String str = "14:21:16";
final Timestamp timestamp =
Timestamp.valueOf(
new SimpleDateFormat("yyyy-MM-dd ")
.format(new Date()) // get the current date as String
.concat(str) // and append the time
);
System.out.println(timestamp);
Output:
2011-03-02 14:21:16.0
Personally, I'd use Joda Time to parse the time to a LocalTime, and add that to today's LocalDate to get a LocalDateTime, then convert that into an Instant using whatever time zone you're interested in. (Or use LocalTime.toDateTimeToday(DateTimeZone).)
Then just create a time stamp using the Timestamp(long) constructor.
There are plenty of other approaches (e.g. using SimpleDateFormat instead of parsing with Joda Time, if you really want...) but ultimately you're likely to want the Timestamp(long) constructor in the end. (The benefit of using Joda Time here is that it's obvious what's being represented at each stage - you're not trying to treat a "time only" as a "date and time" or vice versa.)
Best I can come up with using standard API is not that pretty:
// Get today's date and time.
Calendar c1 = Calendar.getInstance();
c1.setTime(new Date());
// Get the required time of day, copy year, month, day.
Calendar c2 = Calendar.getInstance();
c2.setTime(java.sql.Time.valueOf("14:21:16"));
c2.set(Calendar.YEAR, c1.get(Calendar.YEAR));
c2.set(Calendar.MONTH, c1.get(Calendar.MONTH));
c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH));
// Construct required java.sql.Timestamp object.
Timestamp time = new Timestamp(c2.getTimeInMillis());
Let's see what we've done.
System.out.println(time);
Note that java.sql.Time.valueOf accepts a string of the form "HH:MM:SS" as you require. Other formats would require use of SimpleDateFormat.
Use org.apache.commons.lang.time.DateUtils:
Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
DateFormat df = new SimpleDateFormat("HH:mm:ss");
Date time = df.parse("14:21:16");
Timestamp time = new Timestamp(today.getTime() + time.getTime());
Have a given day (say, unix epoch?) to serve as the day. When you use it, only use the time parameters that you care about, ignoring the day.
Another option would be java.sql.Time
http://download.oracle.com/javase/1.4.2/docs/api/java/sql/Time.htm
String str = "14:21:16";
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date date = formatter.parse(str);
Timestamp timestamp = new Timestamp(date.getTime());
Related
I have a DateTime object DT which stores current time. When I print DT, I want it to only print the time part, ie HH-MM-SS (H = hours, M = minutes, S = seconds) and ignore the date part.
How can I do this ? For that matter, is it even possible to create a date time object which will only contain HH-MM-SS and nothing related to date ? If that is true, then I can simply print it instead of extracting the HH-MM-SS part.
Thanks.
If you only want the time, you should use a LocalTime instead of a DateTime. You can use DateTime.toLocalTime() to get the time part of an existing DateTime.
If you actually want to keep the DateTime but only reveal the time part when formatting, you can create a DateTimeFormatter with a pattern which only includes the time parts, but I'd usually consider this a design smell.
You can use Java date formatter which is in java.util.Date package.
Like :
Date todaysDate = new java.util.Date();
1. // Formatting date into yyyy-MM-dd HH:mm:ss e.g 2008-10-10 11:21:10
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(todaysDate);
2. // Formatting date into yyyy-MM-dd e.g 2008-10-10
formatter = new SimpleDateFormat("yyyy-MM-dd");
formattedDate = formatter.format(todaysDate);
3. // Formatting date into MM/dd/yyyy e.g 10/10/2008
formatter = new SimpleDateFormat("MM/dd/yyyy");
formattedDate = formatter.format(todaysDate);
With Java you can do it like this
Date obj = new Date() ;
System.out.println(new SimpleDateFormat("hh:mm:ss").format(obj)) ;
but it could be an expensive call.
But jodatime gives LocalTime which you can try out.
I have a date that I get from a server formatted in EST like this
05/07/2012 16:55:55 goes month/day/year then time
if the phone is not in EST how can I convert it to the timezone the phone is in?
it would be not problem if I got the time in milliseconds but I dont
EDIT:
ok now the time is not correct when formatting
String sTOC = oNewSTMsg.getAttribute("TOC").toString();
String timezoneID = TimeZone.getDefault().getID();
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("EST"));
String newtimezoneID = TimeZone.getDefault().getID();
Date timestamp = null;
try{
timestamp = format.parse(sTOC);
format.setTimeZone(TimeZone.getDefault());
timezoneID = format.format(timestamp);
}catch(ParseException e){
}
I convert it to "EST" then format that time to the default TimeZone but the time is always off by an hour, not sure why?
Use the following code to get a UNIX timestamp:
String serverResp = "05/07/2012 16:55:55";
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
Date date = format.parse(serverResp);
Now you have the timestamp, which you know how to use.
Here's another question which covers conversion, in case you are curious: Android Convert Central Time to Local Time
Use the DateFormat class to parse the String into a Date. See the introduction to the API document here... http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html
You can then create a Calendar for the Date...
Calendar cal = Calendar.getInstance().setTime(date);
And then you can change the timezone on the Calendar to a different timezone using setTimezone(). Or just get the time in milliseconds, using getTimeInMillis()
Using the Calendar, Date, and DateFormat classes should put you in the right direction.
See the Calendar documentation here... http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html
How to convert Formatted date (yyyy-MM-dd) to Unix time in Java?
I want to declare a date using
Date birthday = new Date(y_birthday, m_birthday, d_birthday);
but this constructor has been deprecated, so I got to use the other constructor which uses Unix timestamp
So, you have the date as a string in the format yyyy-MM-dd? Use a java.text.SimpleDateFormat to parse it into a java.util.Date object:
String text = "2011-12-12";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date date = df.parse(text);
edit If you need a java.sql.Date, then you can easily convert your java.util.Date to a java.sql.Date:
java.sql.Date date2 = new java.sql.Date(date.getTime());
Use a calendar object if you want more control of the date object
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2011);
calendar.set(Calendar.MONTH, 11); // indexed month (December)
calendar.set(Calendar.DATE, 12);
Date date = new Date(calendar.getTime().getTime());
The hours, minutes, seconds etc of the current time will be set though so you may want to set those to 0 (manually per field)
If you're using Java 7 then I think there's some much nicer stuff you can use for handling dates
I want to get the Date in MM/DD/YY format from a timestamp.
I have used the below method but it does not gives proper output
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Long.parseLong(1306249409));
Log.d("Date--",""+cal.DAY_OF_MONTH);
Log.d("Month--",""+cal.MONTH);
Log.d("Year--",""+cal.YEAR);
But its gives the output like below
Date--5
Month--2
Year--1
The correct date is 24 May 2010 for Timestamp - 1306249409
Note - Timestamp is received by a webservice which is used in my application.
Better Approach
Simply Use SimpleDateFormat
new SimpleDateFormat("MM/dd/yyyy").format(new Date(timeStampMillisInLong));
Mistake in your Approach
DAY_OF_MONTH ,MONTH, .. etc are just constant int value used by Calendar class
internally
You can get the date represented by cal by cal.get(Calendar.DATE)
Use the SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String time = sdf.format(date);
What's wrong:
Calendar.DAY_OF_MONTH, Calendar.MONTH etc are static constants used to access those particular fields. (They will remain constant, no matter what setTimeInMillis you provide.)
How to solve it:
To get those particular fields you can use the .get(int field)-method, like this:
Log.d("Month--",""+cal.get(Calendar.MONTH));
As others have pointed out there are more convenient methods for formatting a date for logging. You could use for instance the SimpleDateFormat, or, as I usually do when logging, a format-string and String.format(formatStr, Calendar.getInstance()).
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date);
System.out.println(s);
TimeZone utc = TimeZone.getTimeZone("UTC"); // avoiding local time zone overhead
final Calendar cal = new GregorianCalendar(utc);
// always use GregorianCalendar explicitly if you don't want be suprised with
// Japanese Imperial Calendar or something
cal.setTimeInMillis(1306249409L*1000); // input need to be in miliseconds
Log.d("Date--",""+cal.get(Calendar.DAY_OF_MONTH));
Log.d("Month--",""+cal.get(Calendar.MONTH) + 1); // it starts from zero, add 1
Log.d("Year--",""+cal.get(Calendar.YEAR));
Java uses the number of milliseconds since 1st January 1970 to represent times. If you compute the time represented by 1306249409 milliseconds, you'll discover that it's only 362 days, so your assumptions are wrong.
Moreover, cal.DAY_OF_MONTH holds a constant. Use cal.get(Calendar.DAY_OF_MONTH) to get the day of month (same for other parts of the date).
use String.format which is able to convert long (milliseconds) to date/time string in different formats:
String str;
long time = 1306249409 * 1000L; // milliseconds
str = String.format("%1$tm/%1$td/%1$ty", time); // 05/24/11
str = String.format("%tF", time); // 2011-05-24 (ISO 8601)
str = String.format("Date--%td", time); // Date--24
str = String.format("Month--%tm", time); // Month--05
str = String.format("Year--%ty", time); // Year--11
documentation: format string.
What's the best way to get the number of seconds in a string representation like "hh:mm:ss"?
Obviously Integer.parseInt(s.substring(...)) * 3600 + Integer.parseInt(s.substring(...)) * 60 + Integer.parseInt(s.substring(...)) works.
But I don't want to test that, and reinvent the wheal, I expect there is a way to use DateTimeFormat or other classes from standard libraries.
Thanks!
Based on pakores solution:
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date reference = dateFormat.parse("00:00:00");
Date date = dateFormat.parse(string);
long seconds = (date.getTime() - reference.getTime()) / 1000L;
reference is used to compensate for different timezones and there is no problem with daylight saving time because SimpleDateFormat does NOT use the actual date, it return the Epoc date (January 1st, 1970 = no DST).
Simplifying (not much):
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = dateFormat.parse("01:00:10");
long seconds = date.getTime() / 1000L;
but I would still have a look at Joda-Time...
An original way:
The Calendar version (updated with the suggestions in the comments):
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = dateFormat.parse(string);
//Here you can do manually date.getHours()*3600+date.getMinutes*60+date.getSeconds();
//It's deprecated to use Date class though.
//Here it goes an original way to do it.
Calendar time = new GregorianCalendar();
time.setTime(date);
time.setTimeZone(TimeZone.getTimeZone("UTC"));
time.set(Calendar.YEAR,1970); //Epoc year
time.set(Calendar.MONTH,Calendar.JANUARY); //Epoc month
time.set(Calendar.DAY_OF_MONTH,1); //Epoc day of month
long seconds = time.getTimeInMillis()/1000L;
Disclaimer: I've done it by heart, just looking at the documentation, so maybe there is a typo or two.
joda-time is 1 options. infact i prefer that library for all date manipulations. I was going thru the java 5 javadoc and found this enum class which is simple and useful for you. java.util.concurrent.TimeUnit. look at the convert(...) methods. http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/api/java/util/concurrent/TimeUnit.html
Here is the link to a Java example of time formatting.
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/i18n/format/simpleDateFormat.html