I have seen this question asked multiple times and none of the answers seem to be what i need.
I have a long type variable which has an epoch time stored in it.
What i want to do is convert it to a String
for example if the epoch time stored was for today the final string would read:
17/03/2012
How would i to this?
Convert from epoch to human-readable dateString date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000)); Epoch in seconds, remove '*1000' for milliseconds.
use strict; use warnings; use Time::Piece; my $datestring = '07-06-2019 21:13:00'; my $time = localtime->strptime($datestring, '%d-%m-%Y %H:%M:%S'); my $epoch = $time->epoch; ... my $time = localtime($epoch); my $datestring = $time->strftime('%d-%m-%Y %H:%M:%S');
Hive from_unixtime() is used to get Date and Timestamp in a default format yyyy-MM-dd HH:mm:ss from Unix epoch seconds. Specify the second argument in pattern format to return date and timestamp in a custom format.
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).
Look into SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.format(new Date(myTimeAsLong));
You'd create a Date
from the long
- that's easy:
Date date = new Date(epochTime);
Note that epochTime
here ought to be in milliseconds since the epoch - if you've got seconds since the epoch, multiply by 1000.
Then you'd create a SimpleDateFormat
specifying the relevant pattern, culture and time zone. For example:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
format.setTimeZone(...);
Then use that to format the date to a string:
String text = format.format(date);
Date date = new Date(String);
this is deprecated.
solution
Date date = new Date(1406178443 * 1000L);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
make sure multiply by 1000L
If the method should be portable, better use the default (local time) TimeZone.getDefault()
:
String epochToIso8601(long time) {
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(new Date(time * 1000));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With