This question already has answers here:
Unix epoch time to Java Date object
(7 answers)
Closed 5 years ago.
How can I convert minutes from Unix timestamp to date and time in java? For example, timestamp 1372339860 correspond to Thu, 27 Jun 2013 13:31:00 GMT.
I want to convert 1372339860 to 2013-06-27 13:31:00 GMT.
Edit: Actually I want it to be according to US timing GMT-4, so it will be 2013-06-27 09:31:00.
You can use SimlpeDateFormat to format your date like this:
long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L);
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
The pattern that SimpleDateFormat takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Because a Date provides a getTime() method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)
Java 8 introduces the Instant.ofEpochSecond utility method for creating an Instant from a Unix timestamp, this can then be converted into a ZonedDateTime and finally formatted, e.g.:
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
System.out.println(formattedDtm); // => '2013-06-27 09:31:00'
I thought this might be useful for people who are using Java 8.
You need to convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
Related
This question already has answers here:
Java string to date conversion
(17 answers)
Closed 5 years ago.
I try to use java.util.Date date = Date.from( Instant.parse(minDates)); to parse the date string given in format Wed Jan 17 2001 00:00:00 GMT 0530.
I am not able to figure out, how to do that in JAVA.
The want to convert the given date string in given format
2013-05-22T00:00:00
May be i am not able to figure it out, properly. If someone have way to do that suggest me in Java Only.
Here is the solution:
String dateToParse = "Wed Jan 17 2001 00:00:00 GMT 0530";
SimpleDateFormat in = new SimpleDateFormat("EEE MMM dd YYYY HH:mm:ss");
SimpleDateFormat out = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ss");
Date date = in.parse( dateToParse );
System.out.println( out.format( date ) );
It will work if all dates are in the same timezone (GMT 0530)
Else it should be modified to support it, but I suppose you have the same timezone.
You can do that by using SimpleDateFormat 'parse' API.
You can initialize your SimpleDateFormat with any valid time format such as yyyy-MM-dd HH:mm:ss z and then parse any string which adheres to this format.
reff. to http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
One addition tip, use JodaTime as the Date and SDF in Java are getting deprecated: http://www.joda.org/joda-time/
If you are using Java 8+, You can use java.time.OffsetDateTime (or Instant...) instead of java.util.Date, which is incredibly easy.
OffsetDateTime odt = OffsetDateTime .parse("2013-05-22T00:00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME);
Note that the second argument is optional in this case but you could have to specify one (with timezone id for example).
There is a solution without external which works with older version of Java and that manages timezones well. It consists of using JAXB's DataTypeConverter.
Date date = javax.xml.bind.DatatypeConverter.parseDateTime("2013-05-22T00:00:00+01:00").getTime();
Note that DatatypeConverter.parseDateTime returns a Calendar. You just need to call its getTime() method to convert is to a Date.
I have date 2015-12-25 23:59:59 in the form of epoch milliseconds 1451087999000, And I want the date part only i.e. 2015/12/25, how do I do that efficiently might be with the JODA time library which is nowdays standard for dealing with Date time in java.
I have this code which works in most the case but when time is like 23:59:59 it gives me the next date (as in my case it gives 2015-12-26 with input of 2015-12-25 23:59:59)-
String dateInMilliSeconds = "1451087999000";
String dateInYYYYMMDDFormat = DateHelper.convertDateFormat(new Date(Long.valueOf(dateInMilliSeconds)),DateHelper.yyyy_MM_dd);
DateHelper.convertDateFormat() -
public static final String yyyy_MM_dd = "yyyy-MM-dd";
public static String convertDateFormat( Date date, String outputFormat )
{
String returnDate = "";
if( null != date )
{
SimpleDateFormat formatter = new SimpleDateFormat(outputFormat);
returnDate = formatter.format(date);
}
return returnDate;
}
You can use localDate from java 8
LocalDate date = Instant.ofEpochMilli(dateInMilliSeconds).atZone(ZoneId.of(timeZone)).toLocalDate();
I should like to make two points:
Time zone is crucial.
Skip the outdated classes Date and SimpleDateFormat.
My suggestion is:
String dateInMilliSeconds = "1451087999000";
LocalDate date = Instant.ofEpochMilli(Long.parseLong(dateInMilliSeconds))
.atOffset(ZoneOffset.UTC)
.toLocalDate();
System.out.println(date);
This prints
2015-12-25
Please note that you get your desired output format for free: LocalDate.toString() produces it. If you want to be able to produce different output formats, use a DateTimeFormatter.
Time zone
Your millisecond value isn’t just equal to 2015-12-25 23:59:59. It is equal to this date and time in UTC, so you need to make sure that your conversion uses this time zone offset. When I run your code from the question on my computer, I incorrectly get 2015-12-26 because my computer is in the Europe/Copenhagen time zone.
JSR-310 AKA java.time
Joda-Time was the widely acknowledged better alternative to the original date and time API from Java 1 that many considered poor and troublesome. The Joda-Time project is now finished because the modern Java date and time API known as JSR-310 or java.time came out three and a half years ago, so they recommend we use this instead. So my code does.
The timestamp 1451087999000 is 2015-12-25 23:59:59 in UTC. In your code, you're not specifying the timezone when you format it with a SimpleDateFormat, so it's formatted in your local timezone.
With Joda Time:
String dateInMilliSeconds = "1451087999000";
LocalDate date = new LocalDate(Long.parseLong(dateInMilliSeconds), DateTimeZone.UTC);
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
String result = formatter.print(date);
This question already has answers here:
java.sql.Timestamp: changing timezone of Timestamp
(2 answers)
Closed 6 years ago.
I get timestamps as a String in a stream and they are of the format "2016-12-08 05:44:48 <timezone like IST, UTC>" and "2016-12-08 05:44:48 <timezone like +0000>"
I want to convert the string to java.sql.Timestamp so I wrote a function as follows
private static Timestamp convertToTimestamp(String s) throws ParseException{
String dateFormat = new String("yyyy-MM-dd hh:mm:ss z");
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Date d = sdf.parse(s);
return new Timestamp(d.getTime());
}
When I run
Timestamp t = convertToTimestamp("2016-12-08 05:44:48 UTC");
System.out.println(t);
The output is 2016-12-08 11:14:48.0
It is automatically converting into IST (Probably my JVM default).
How to make the change so that the output time not changed to IST and is same as input?
Java's java.util.Date and java.sql.Timestamp do not store timezone.
They always track time in UTC.
When parsing a date string that includes a timezone, the string is correctly parsed and adjusted from the given timezone to UTC.
When parsing a date string without timezone, the string is parsed in the JVM's default timezoneand converted to UTC, unless another timezone has been explicitly given to the date parser (commonly SimpleDateFormat).
When displaying (aka formatting) a Date/Timestamp, it will be shown in the JVM's default timezone, unless otherwise specified.
The Date/Timestamp objects cannot store a timezone, so they cannot remember what the original timezone was.
If you need that, use Java 8's ZonedDateTime.
You have to ignore the time-zone when parsing the date
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
This question already has answers here:
convert String in time to Time object without Date
(3 answers)
Closed 6 years ago.
I am trying to convert a 6 digits String to Time without the date with SimpleDateFormat but I am getting the date of 01.01.1970 after converting the time. How can I just get the time stored in the time variable without the date?
Code
String timeString = "004500";
SimpleDateFormat formater = new SimpleDateFormat("hhmmss");
Date time= formater.parse(timeString );
you can use LocalTime which is what you want. You can parse a standard date like this:
String str = "1986-04-08 12:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
LocalTime time - dateTime.toLocalTime();
If you only have a time to parse you can use LocalTime.parse() method.
Note that this is only available starting from Java 8. You can also add Joda Time as a dependency if you are not using Java 8 yet.
I am converting epoch format time to the normal format, but when I convert it to date I get, MM-dd-yyyy hh:mm:ss.
If I want to single out just the date or the time I have to use SimpleDateFormat. But this returns a String. I was wondering if there was a way to make this string a Date type.
The type java.util.Date is actually a timestamp, it is not much more than a wrapper for a number of milliseconds since 01-01-1970, 00:00:00 UTC. (The class name Date is unfortunately badly chosen).
It is not very well suited for holding just a date or just a time value.
If you are using Java 8, use the new date and time API (package java.time); use for example LocalDate if you need to store a year/month/day, or a LocalTime if you need to store just a time-of-day (hours, minutes, seconds, milliseconds).
If you are using Java 7 or older, consider using the equivalent classes in the Joda Time library.
You can format the date as MM-dd-yyyy HH:mm:ss not (MM-dd-yyyy hh:mm:ss)
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
DateFormat dateformat= new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
Date date = dateformat.parse("01-25-1988 23:54:59");
System.out.println(date);
System.out.println(dateformat.format(date));