after parsing timestamp its adding milliseconds in timestamp in java - java

I want to convert the string time to Timestamp Object
My code for parsing is like this
String ts = "120918 10:35:45";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd hh:mm:ss");
java.util.Date parsedDate = dateFormat.parse(ts);
//parsing timestamp
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
System.out.println("timestamp after parsing :: "+timestamp);
It gives me result :-- timestamp after parsing :: 2012-09-18 10:35:45.0
But I do not want milliseconds part. I want only this -- 2012-09-18 10:35:45
Please help me in removing milliseconds part.

Timestamp is a container of milliseconds. The toString() is formatting it's contains based on what it thinks is best to be displayed.
If you want to format the value, you should use a date formatter and not use the value returned by the Timestamp object.
SimpleDateFormat noMilliSecondsFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(noMilliSecondsFormatter.format(timestamp));
nb. The value you have (after you've converted it) does not contain any milliseconds anyway...

My guess, probably you didn't use "noMilliSecondsFormatter" in println().

The method java.util.Date.getTime() according to its javaDoc:
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object
Therefore, when you create the TimeStamp object, you are already passing mileseconds.

Related

Creating a datetime object in a particular timezone in JodaTime

I have a date, timezone and time as Strings, and I want to construct a JodaTime object with that date and time for that timezone. The code I have written is
String dateString = "2016-06-02";
String time = "01:00:00";
String timezone = "Australia/Brisbane";
DateTime dateInTimezone = DateTime.parse(dateString+" "+time,DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
.withZone(DateTimeZone.forID(timezone));
I would expect dateInTimezone to be created with value 2016-06-02T01:00:00.000+10:00 but it gets created with value 2016-06-02T18:00:00.000+10:00. My systems timezone is in America\Los_Angeles. From what I understand it takes the time I pass as a parameter in my systems timezone and converts that to the timezone I specify. Probably thats why 01:00:00 got internally converted to 18:00:00.
How do I create a joda time object with specified time and specified timezone, without any conversions?
Add the timezone to your formatter before parsing:
String dateString = "2016-06-02";
String time = "01:00:00";
String timezone = "Australia/Brisbane";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
.withZone(DateTimeZone.forID(timezone));
DateTime dateInTimezone = DateTime.parse(dateString+" "+time, formatter);
Another option is to do it your way, but call DateTime.withZoneRetainFields(), but then there's the risk of the parse failing if it falls out on an invalid date (e.g. between a DST gap) in the initial timezone.

Converting String to Date

How can I parse the following String "1394133302" which correspond of Date.toString value to a Date value (java utils).
Is it possible with a SimpleDateFormat?
Use code below
new Date(Long.valueOf("1394133302"))
PS. It seems you date string is in second, maybe you want this(convert it to millesecond!)
new Date(Long.valueOf("1394133302") * 1000L)
Just feed it back into the Date constructor:
long dateAsLong = Long.parseLong( "1394133302");
Date someDate = new Date(dateAsLong);
SimpleDateFormat is used for formatting Date value, in your case you already have a long date value in terms of Stringconvert it to Long and pass it directly to Date constructor to get date Object
Date dt = new Date(Long.valueOf("1394133302"));

Converting a date string from a timezone to different time zone

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 a date to UTC

I need to change de format of a date to UTC format.
File file = new File();
...
file.lastModified();
I need to convert the lastModified date of a file in UTC format.
String lv_dateFormateInUTC=""; //Will hold the final converted date
SimpleDateFormat lv_formatter = new SimpleDateFormat();
lv_formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
lv_dateFormateInUTC = lv_formatter.format(lv_localDate);
Something like that...!!
Quite simply:
Date date = new Date(file.lastModified())
This works because the long value returned by File.lastModified() represents the number of milliseconds since the epoch (00:00:00 GMT, January 1, 1970) as stated in the Javadoc. And the same is true of java.util.Date. So they are both in UTC/GMT already. When a date is converted to a string such as via Date.toString() or a DateFormat object, it's typically expressed in the local timezone, but the long value it stores is timezone-agnostic.

Java: convert a time from today to a timestamp

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());

Categories