How do I convert timestamp string to local time string? - java

I have timestamp string: "1989-01-01 00:00:00" and i need convert it to local date format.
I execute:
SimpleDateFormat TIMESTAMPFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat.getDateFormat(getContext()).format(TIMESTAMPFORMAT.parse("1989-01-01 00:00:00"));
And getDateFormat returns 31.12.1988
Why?
How can I receive 01.01.1989???

In order to skip time-zone when formatting, I would suggest you to set it to default as below:
SimpleDateFormat TIMESTAMPFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TIMESTAMPFORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));

This is probably to do with the time zones involved. I strongly suspect that you're formatting in a different time zone to the one you're using for parsing, and the value goes to before midnight, basically. If you can use the same time zone on both, it's likely to work.
If you possibly can, I'd encourage you to use Joda Time instead though - you really want a LocalDate.

Related

Format a String to a Fixed Date at UTC+0 in Java

I want to convert a String date - 2017-01-01 to java.util.Date with UTC+0. So, what I am expecting is.
"2017-01-01" -> 2017-01-01T00:00:00 UTC+0100
Here is how I am trying to do, but as my default Timezone is UTC+1, I am getting that 1 hour added to the Date.
Date d = Date.from(Instant.parse("2017-01-01T00:00:00Z"));
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss 'UTC'ZZZZZ");
String output = sf.format(d);
System.out.println(output);
Here is the output:
2017-01-01T01:00:00 UTC+0100
Can somebody help?
Your code is mixing oldfashioned and modern classes. Date and SimpleDateFormat are long outdated. Instant is modern (from 2014). I recommend you stick to the modern ones unless you are working with an old API that requires and/or gives you an instance of an oldfashioned class. So the answer is
String output = LocalDate.parse("2017-01-01")
.atStartOfDay(ZoneOffset.ofHours(1))
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss 'UTC'XX"));
The result is the one you asked for
2017-01-01T00:00:00 UTC+0100
The code is not really shorter than yours, but once you get used to the fluent style you will find it clearer and more natural. The room for confusion and errors is considerably reduced.
If you want the start of day in whatever time zone the user is in, just fill in ZoneId.systemDefault() instead of ZoneOffset.ofHours(1).
LocalDate parses your date string — "2017-01-01" — without an explicit format. The string conforms to ISO 8601, and the modern classes use this standard as their default for parsing and also for their toString().
You can set the timezone first and then format it.
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sf.parse(d);
And now format as per your requirements:
String output = sf.format(date);
System.out.println(output);
I wonder please try this also:
Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
date = cal.getTime();

SimpleDateFormat not showing the right date format

I have a DateTime field in my SQL database holding and when I try to show it in my JSP page and format it using "dd-MM-yyyy hh:mm:ss", it displays correctly only the date part. For example, for the date "2012-01-19 12:13:48" stored in the database it shows "19-01-2012 12:00:00". What may be the problem?
Code:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
sdf.format(rs.getDate("comment_date")); //rs -> ResultSet
From the javadoc for java.sql.Date:
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
In order to preserve time information as well, you should be using java.sql.Timestamp. In other words, change rs.getDate() to rs.getTimestamp().
An interesting date/time library you could have a look at is Joda Time. It solves many issues of the date/time implementations in the standard library.

I want to get a formatted Date in Java

I want to get a new Date object with a SimpleDateFormat applied to it. I would like to do something like:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
Date today = new Date();
today = myFormat.format(today);
I can't do this, because today is a Date, and format returns a String. I also have tried:
Date today;
SimpleDateFormat myFormat = new SimpleDateFormat("dd MMM yyyy kkmm");
try{
today = myFormat.parse((new Date()).toString());
}catch(Exception e){
}
This isn't a good solution, because when I try to use today elsewhere Java complains that today may not have been instantiated. What is a good way to change the format of a Date object (while still keeping it a Date object, and not turning it to a string)?
You are looking at Format and Date wrongly.
Date does not contain format. Date is just a class containing date info like date, month, hours, sec etc.
SimpleDateFormat is the one which tells you the string representation of Date. But there is no date associated with it.
So the idea is when you have to display date or have to store date in some string representation, you will use SimpleDateFormat and pass it the date you want string representation for.
One benefit of doing this way is that, I can use same Date object and can show two different string representations (using two different instances of SimpleDateFormat). And also viceversa, having defined one SimpleDateFormat instance, I can format multiple dates.
Edit:
Now if you want to strip some info from the date. Use
Calendar rightNow = Calendar.getInstance();
Calendar cal = new GregorianCalendar(
rightNow.get(YEAR),
rightNow.get(MONTH),
rightNow.get(DAY_OF_MONTH));
Date now = cal.getTime();
There are other good soln like JodaTime
Ref:
GregorianCalendar
Calendar
Joda Time
I think what you are trying to achieve does not make sense.
A Date object represents time. You can not format it. But, you can get it's string representation in certain format. Like with myFormat.format(today).
I think you're misunderstanding something here about what the Date object is. Date simply holds the information about a point in time - it doesn't have a format at all. When it comes to the String representation of a Date, this is where formatting comes into play. Only worry about the formatting when you are:
Parsing a String representation into a Date object.
Converting a Date back into String representation to display it in a certain way.
Your question doesn't make sense. Formatting a date by definition means converting it to a string using a specific format. The Date object can stay as a Date object. It is only at the point where you wish to convert it to a String that you need to do any formatting.
you cannot associate a format to a Date object instead you can only apply the formats while displaying or other activities,,
Do all processing in the Date object itself and while displaying alone change to the required format,,

Code to convert seconds to Date and time combination in java

I have seconds like below:
1320130800
I need to convert the value into Date and Time Combination format. While formatting I got the result as follows:
Tuesday,November 1,2011 2:00,AM
But the correct result is as follows:
Tuesday,November 1,2011 7:00,AM
For the above format conversion I used the below code:
long millis = 1320130800*1000;
Date date = new Date(millis);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm a");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
Can any one guide me to get the correct answer?
Sounds like it's just a time zone issue - you need to set the time zone for the formatter:
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
(Note that in your sample code, long millis = 1320130800*1000; doesn't work as it performs the multiplication in 32-bit arithmetic; you need something like long millis = 1320130800L*1000;.)
Use the Calendar API instead.
After you have the Date object, construct a Calendar object (getInstance() returns one with the default Time Zone) and do setDate(Date) on it and parse it like that.
Alternatively, you can take a look at Joda Time APIs since they are easy to use.
Regards!

format as GMT/UTC time when default timezone is something else

I have a program which needs to run under my local timezone for other reasons, but for one procedure i need to output dates using a SimpleDateFormat in GMT.
what is the tidiest way to do this?
Using the standard API:
Instant now = Instant.now();
String result = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
.withZone(ZoneId.of("GMT"))
.format(now);
System.out.println(result);
The new DateTimeFormatter instances are immutable and can be used as static variables.
Using the old standard API:
TimeZone gmt = TimeZone.getTimeZone("GMT");
DateFormat formatter = DateFormat.getTimeInstance(DateFormat.LONG);
formatter.setTimeZone(gmt);
System.out.println(formatter.format(new Date()));
Given that SimpleDateFormat isn't thread-safe, I'd say that the tidiest way is to use Joda Time instead. Then you can create a single formatter (calling withZone(DateTimeZones.UTC) to specify that you want UTC) and you're away:
private static DateTimeFormatter formatter = DateTimeFormat.forPattern(...)
.withZone(DateTimeZone.UTC);
...
String result = formatter.print(instant);
This has the other benefit that you can use Joda Time elsewhere in your code, which is always a good thing :)

Categories