Convert Unix time into readable Date in Java - java

What is the easiest way to do this in Java? Ideally I will be using Unix time in milliseconds as input and the function will output a String like
November 7th, 2011 at 5:00 PM

SimpleDateFormat sdf = new SimpleDateFormat("MMMM d, yyyy 'at' h:mm a");
String date = sdf.format(myTimestamp);

I wanted to convert my unix_timestamps like 1372493313 to human readable format like Jun 29 4:08.
The above answered helped me for my Android app code. A little difference was that on Android it recommends to use locale settings as well, and my original unix_timestamp was in seconds, not milliseconds, and Eclipse wanted to add try/catch block or throw exception. So my working code has to be modified a bit like this:
/**
*
* #param unix_timestamp
* #return
* #throws ParseException
*/
private String unixToDate(String unix_timestamp) throws ParseException {
long timestamp = Long.parseLong(unix_timestamp) * 1000;
SimpleDateFormat sdf = new SimpleDateFormat("MMM d H:mm", Locale.CANADA);
String date = sdf.format(timestamp);
return date.toString();
}
And here is the calling code:
String formatted_timestamp;
try {
formatted_timestamp = unixToDate(unix_timestamp); // timestamp in seconds
} catch (ParseException e) {
e.printStackTrace();
}

java.util.Date date = new java.util.Date((long) time * 1000L);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

Related

Android JodaTime convert UTC to User's time

I am stuck while solving this naive scenario. Here is what I designed to convert UTC to local time.
public static DateTime timezoneAwareDate(Date date){
DateTime input = new DateTime(date,DateTimeZone.UTC);
DateTime output = input.withZone(DateTimeZone.getDefault());
Log.d(niftyFunctions.LOG_TAG,new SimpleDateFormat("yyyy-mmm-dd hh:mm").format(output.toDate()));
return output;
}
Here is what my input date looks like in UTC, coming from server:
2015-07-28 16:30
But here is what I am getting on my phone which is in IST from Log.d statement:
2015-030-28 07:30
I am going crazy about what's actually happening. Any help?
So I went with Joda-less solution using just the native libs. Here is the function
/**
* Returns localtime for UTC
*
* #param date
* #return
*/
public static Date timezoneAwareDate(String date){
// create simpledateformat for UTC dates in database
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date output;
// parse time
try{
output = simpleDateFormat.parse(date);
}catch (Exception e){
// return current time
output = new Date();
}
return output;
}

Processing Java Strings and Dates

I need to process a list of Strings which may or may not be times. When I do receive a time, it will need to be converted from "HH:mm:ss" to number of milliseconds before processing:
final String unknownString = getPossibleTime();
final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setLenient(false);
try {
final Date date = dateFormat.parse(unknownString);
//date.getTime() is NOT what I want here, since date is set to Jan 1 1970
final Calendar time = GregorianCalendar.getInstance();
time.setTime(date);
final Calendar calendar = GregorianCalendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
calendar.set(Calendar.SECOND, time.get(Calendar.SECOND));
final long millis = calendar.getTimeInMillis();
processString(String.valueOf(millis));
}
catch (ParseException e) {
processString(unknownString);
}
This code works, but I really dislike it. The exception handling is particularly ugly. Is there a better way to accomplish this without using a library like Joda-Time?
public static long getTimeInMilliseconds(String unknownString) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = dateFormat.format(Calendar.getInstance().getTime());
DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return timeFormat.parse(dateString + " " + unknownString).getTime();
}
Handle the ParseException outside of this method however you'd like. I.e. ("No time information provided"... or "unknown time format"... etc.)
.getTime() returns the time in milliseconds. It's part of the java.util.Date API.
Why don't you first check if the input is actually of HH:mm:ss format. You can do this by trying match input to regex [0-9]?[0-9]:[0-9]?[0-9]:[0-9]?[0-9] first and if it matches then treat it as date otherwise call processString(unknownString);

Fast way to parse a Long date into Month-Day-Year String

How do you parse a Long date like: 1366222239935 into a String of space-separated Month-Day-Year? Like into "Apr 18 2013"
Passing it on a java.util.Date and to a String will give a String of date which contains so many info that I don't need for rendering in my GWT application.
Need to do this style since I will be passing the result into 3 <span> elements; so actually the space-separated date will be split into parts:
Month
Day
Year
As gwt won't support SimpleDateFormat
instead use Gwt DateTimeFormat
DateTimeFormat f = DateTimeFormat.getFormat("dd-MMM-yyyy");
String datestring =f.format(dateGeneratedbyLong);
And make sure the DateTimeFormat import also which you can use both client and server side .
There is another class with same name but package is different which is client(restricts you to use on client side only )
try to use SimpleDataFormat check http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html>
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");
String dateAsString = simpleDateFormat.format(new Date());
You could convert it to a Date and then manually build your String like this.-
Date date = new Date(timeInMils);
String res = date.get(Calendar.MONTH) + " " +
date.get(Calendar.DAY_OF_MONTH) + " " +
date.get(Calendar.YEAR);
That Long number is simply the number of milliseconds since the JavaScript epoch (1/1/1970 at midnight, UTC time). So, instead of parsing it, use the constructor for the Date object:
var myDate = new Date(1366222239935);
alert(myDate);
That will show "Wed Apr 17 2013 11:10:39 GMT-0700 (Pacific Daylight Time)". I am in PST, but it will default to whatever timezone you have in your locale settings.
Inside a GWT app in Java, simply do:
Date date=new Date(1366222239935);
Then you can use SimpleDateFormat to render it as "dd/MM/yy".
See http://www.w3schools.com/jsref/jsref_obj_date.asp
Do like this
Date d = new Date();
d.setTime(1366222239935l);
System.out.println(d);
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd yyyy");
try {
System.out.println(sdf.format((d)));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long diff = 1366222239935l;
Date date = new Date(diff);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
System.out.println(sdf.format(date));

Getting device's local timezone

2010-06-14 02:21:49+0400 or 2010-06-14 02:21:49-0400
is there a way to convert this string to the date according to the local machine time zone with format 2010-06-14 02:21 AM
Adding to what #org.life.java and #Erica said, here's what you should do
String dateStr = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
TimeZone tz = TimeZone.getDefault();
sdf.setTimeZone(tz);
Date date = sdf.parse(dateStr);
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String newDateStr = sdf.format(date);
System.out.println(newDateStr);
Then newDateStr will be your new date formatted string.
UPDATE #xydev, the example I gave you works, see the full source code below:
/**
*
*/
package testcases;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* #author The Elite Gentleman
*
*/
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String dateStr = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
TimeZone tz = TimeZone.getDefault();
sdf.setTimeZone(tz);
Date date = sdf.parse(dateStr);
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String newDateStr = sdf.format(date);
System.out.println(newDateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output: 2010-06-14 08:21:49 AM
Using SimpleDateFormat
String string1 = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ")
sdf.setTimeZone(tz);
Date date = sdf.parse(string1);
Note: I am not sure the same class is available in andriod.
You can do all sorts of fancy formatting and localisation of dates using the DateFormat class. There's very good, complete documentation at the start of the API page here:
http://download.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html
Most regular cases can be handled with the built in SimpleDateFormat object. Its details are here:
http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
The SimpleDateFormat output pattern string for the example you have above would be:
yyyy-MM-dd hh:mm a
Be careful that if you are running on the emulator your timezone is always GMT. I just spent 2 hours in trying to understand why my application does not give me the right time (the one my computer displays) until I realized it is because of the emulator.
To check you are running on the emulator use
if (Build.PRODUCT.contains("sdk")){
// your code here for example if curtime has the emulator time
// since midnight in milliseconds then
curtime += 2 * 60 * 60 * 1000; // to add 2 hours from GMT
}

How to format a date String into desirable Date format

I was trying to format a string into date.
For this I have written a code:-
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(sdf.format( cal.getTime() ));
This is fine..
But now I want to convert a string into a date formatted like above..
For example
String dt="2010-10-22";
And the output should be like this:-
2010-10-22T00:00:00
How do I do this?
String dt = "2010-10-22";
SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition ps = new ParsePosition(0)
Date date = sdfIn.parse(dt, pos)
SimpleDateFormat sdfOut = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(sdfOut.format( date ));
This should do it for you, remember to wrap it in a try-catch block just in case.
DateFormat dt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try
{
Date today = dt.parse("2010-10-22T00:00:00");
System.out.println("Your Date = " + dt.format(today));
} catch (ParseException e)
{
//This parse operation may not be successful, in which case you should handle the ParseException that gets thrown.
//Black Magic Goes Here
}
If your input is going to be ISO, you could also look at using the Joda Time API, like so:
LocalDateTime localDateTime = new LocalDateTime("2010-10-22");
System.out.println("Formatted time: " + localDateTime.toString());
The same class you use for output formatting of dates can also be used to parse dates on input.
SimpleDateFormat reference
To use your example, to parse the sample date:
String dt = "2010-10-22";
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dateFormatter.parse(dt));
The fields that are not specified (ie. hour, minutes, etc) will be 0. So your same code can be used to format the date on output.
Date Format Example
Containing the Conversion of String Date object from one format to another

Categories

Resources