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!
Related
DynamoDB API documentation tells that a supported date should be a String like:
Date (as ISO8601 millisecond-precision string, shifted to UTC)
How do I get this current Date format in Java?
I saw similar things, but they are not quite exactly:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
Is millisecond precision really necessary?
Hopefully I won't need to add Joda for this.
Need a time stamp, to add it to my Range Primary Key.
Need this to put/insert into the Db.
Using Joda,(planned to avoid it) this code seems to do the trick:
DateTime dt = new DateTime(DateTimeZone.UTC);
DateTimeFormatter fmt = ISODateTimeFormat.basicDateTime();
String str = fmt.print(dt);
//20140710T160939.473Z
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.
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,,
I've tried a million different ways of doing this, but with no avail. Any help would be much appreciated.
long millis = getMillisFromServer();
Date date = new Date(millis);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
String formatted = format.format(date);
The above doesn't work.
basically, what I want to do is, get the epoch time and convert it to Australian time. My local time is +05.30 but of course I don't want this to be a factor which contributes to this conversion.
EDIT-
Output when I run your exact code,
epoch 1318388699000
Wed Oct 12 08:34:59 GMT+05:30 2011
12/10/2011 03:04:59
12/10/2011 14:04:59
EDIT: Okay, so you don't want your local time (which isn't Australia) to contribute to the result, but instead the Australian time zone. Your existing code should be absolutely fine then, although Sydney is currently UTC+11, not UTC+10.. Short but complete test app:
import java.util.*;
import java.text.*;
public class Test {
public static void main(String[] args) throws InterruptedException {
Date date = new Date(1318386508000L);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
System.out.println(formatted);
format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
formatted = format.format(date);
System.out.println(formatted);
}
}
Output:
12/10/2011 02:28:28
12/10/2011 13:28:28
I would also suggest you start using Joda Time which is simply a much nicer date/time API...
EDIT: Note that if your system doesn't know about the Australia/Sydney time zone, it would show UTC. For example, if I change the code about to use TimeZone.getTimeZone("blah/blah") it will show the UTC value twice. I suggest you print TimeZone.getTimeZone("Australia/Sydney").getDisplayName() and see what it says... and check your code for typos too :)
Here’s the modern answer (valid from 2014 and on). The accepted answer was a very fine answer in 2011. These days I recommend no one uses the Date, DateFormat and SimpleDateFormat classes. It all goes more natural with the modern Java date and time API.
To get a date-time object from your millis:
ZonedDateTime dateTime = Instant.ofEpochMilli(millis)
.atZone(ZoneId.of("Australia/Sydney"));
If millis equals 1318388699000L, this gives you 2011-10-12T14:04:59+11:00[Australia/Sydney]. Should the code in some strange way end up on a JVM that doesn’t know Australia/Sydney time zone, you can be sure to be notified through an exception.
If you want the date-time in your string format for presentation:
String formatted = dateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));
Result:
12/10/2011 14:04:59
PS I don’t know what you mean by “The above doesn't work.” On my computer your code in the question too prints 12/10/2011 14:04:59.
Please take care that the epoch time is in second and Date object accepts Long value which is in milliseconds.
Hence you would have to multiply epoch value with 1000 to use it as long value .
Like below :-
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
Long dateLong=Long.parseLong(sdf.format(epoch*1000));
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 :)