I am working on date format application, i have one T date format but i am not able to parse this format.
try {
String dtStart = "2016-07-20T11:51:31.744Z";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
if (dtStart != null) {
Date date = format.parse(dtStart);
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);
String promoPendingDay = "" + myCal.get(Calendar.DAY_OF_MONTH);
int promoPendingMonth = myCal.get(Calendar.MONTH) + 1;
String promoPendingYear = "" + myCal.get(Calendar.YEAR);
mMessageStartDateLabel.setText(promoPendingDay + "/" + promoPendingMonth + "/" + promoPendingYear);
}
} catch (ParseException e) {
e.printStackTrace();
}
every time i am getting one exception java.text.ParseException: Unparseable date:
Please kindly go through my code and suggest me some solution.
Here a solution applying two changes. One change is to add the fractional seconds, another change is to set the UTC-timezone.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
format.setTimeZone(TimeZone.getTimeZone("GMT")); // very important, input Z means UTC+00
Related
In my application i should show hour and minute and i get this numbers from server with this sample :
Json :
{
data:{
time:84561
}
}
i should get this number from time and show it with this format
**hh : mm : ss**
I can get number of time, but i can't convert this to **hh : mm : ss** .
How can i it?
long timeSec= 84561;// Json output
int hours = (int) timeSec/ 3600;
int temp = (int) timeSec- hours * 3600;
int mins = temp / 60;
temp = temp - mins * 60;
int secs = temp;
String requiredFormat = hours+ ": "+mins+": "+secs;//hh:mm:ss formatted string
Java 9 answer
Duration time = Duration.ofSeconds(87561);
String hms = String.format("%02d : %02d : %02d",
time.toHoursPart(),
time.toMinutesPart(),
time.toSecondsPart());
Unfortunately in Java 8 Duration does not lend itself well to formatting. The methods I use in the snippet are introduced in Java 9 and will calculate the values for hh, mm and ss. Then String.format() does the rest.
I know you cannot use this on Andriod (yet), but I wanted to have this answer stand here for others who can use Java 9, now or in the future.
Very simple
If this is unix time then it will be converted into human readable time format with this snippet.
String relavtiveTimeString = String.valueOf(DateUtils.getRelativeTimeSpanString(unixTime));
You can use new Date(unix); and with below function you can get formatted date. You can format in different style.
//This mehtod convert the date into standard date like : 2017-12-23
public static String getformateDate(Date dateObject) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(dateObject);
}
For more information check this link already answer :
Convert unix time stamp to date in java
Referance:
https://developer.android.com/reference/android/text/format/DateUtils.html
https://developer.android.com/reference/android/text/format/Time.html
Pass your Number or timestamp and convert to milliseconds for hour and minute.use the below code.
public static String getCurrentTimeStamp(String mCurrentTime) {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm a z");
TimeZone tz = TimeZone.getDefault();
format.setTimeZone(tz);
// System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
SimpleDateFormat dateParser = new SimpleDateFormat("dd/MM/yyyy hh:mm a z");
Date dateTime = null;
try {
dateTime = dateParser.parse(format.format(Long.parseLong((mCurrentTime)) * 1000));
Log.e("Starttime", "Starttime" + format.format(dateTime));
return format.format(dateTime);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
Try This Logic Use it As per Requirement
public class Test {
public static void main(String[] args) {
String json = "{\n" +
" data:{\n" +
" time:84561\n" +
" }\n" +
"}";
Date date = new Gson().fromJson(json, Date.class);
long milli = date.getTime() * 1000;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println(simpleDateFormat.format(new java.util.Date(milli)));
}
class Date implements Serializable{
int time;
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
}
Output
05:30:00
If you want to download Gson jar download it from
here
I'm learning Android a simple screen with user Information like name,Date of Birth and so on.
All are Text View and Edit Text.
In my pojo Date of Birth datatype is String.
When I enter date and try to get the date it is showing as some long number I this it is date and time in milliseconds.
Can any one help me to solve this.
If i understand your problem.. Try this...
Date d1 = new Date();
d1.setTime(time_in_milliseconds);
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
And then you can get day,month, year..
int number_of_day = cal.get(Calendar.DAY_OF_MONTH)
Check this :
public Date getDateByFormat(String time, String format) {
if (time == null || "".equals(time)) return null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
return sdf.parse(time);
} catch (ParseException e) {
Log.d(Constants.TAG, "Could not parse date: " + time + " Due to: " + e.getMessage());
}
return null;
}
here format is your date string format. Like "yyyy-MM-dd HH:mm:ss"
I have two strings, the first one contains an actual date, and the second one contains a date format.
I want to compare both the strings. Here is my code:
for current date
Date referenceDate = new Date();
Calendar c = Calendar.getInstance();
c.setTime(referenceDate);
c.add(Calendar.MINUTE, -30);
//c.getTime();
//System.out.println("Date class"+c.getTime());
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
currentDateandTime = sdf.format(c.getTime());
System.out.println("Simple Date Format "+currentDateandTime);
and 2nd date code is here
private void setDate() {
try {
sbMain = obj.get("date_of_report").toString().split(" ");
} catch (JSONException e) {
}
String[] sb = sbMain[0].split("-");
String[] sb2 = sbMain[1].split(":");
System.out.println("Alert Time : " + sb[0] + " " + sb[1] + " " + sb[2] + " " + sb2[0] + ":" + sb2[1] + ":" + sb2[2]);
}
When you have all the components of your second date, e.g Day,time,Month and Year then use the same Calendar class to obtain date object by setting correct time and date components you retrieved, now you have two valid instances of your dates, get the values of both in Millis, and perform whatever comparision you want.
I am debugging a android framework.
I pull out dropbox logs from device and it's created in /data/system/dropbox.
Log file name is printed like this format.
event_data#1362451303699
1362451303699 is timestamp and i want to change it like 05/03/2013 16:00 for legibility.
How can i convert this timestamp?
Is there any code needs to be changed?
Any help will be much appreciated.
use: Date date = new Date(timestamp);
Edit full code:
String wantedDate = "";
String log = "event_data#1362451303699";
int index = log.indexOf("#");
if(index != -1) {
index = index + 1; // skip # symbol
if(index < log.length()) { // avoid out of bounds
String logtime = log.substring(+1);
try {
long timestamp = Long.parseLong(logtime);
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = new Date(timestamp);
wantedDate = df.format(date);
} catch (NumberFormatException nfe) {
// not a number
}
}
}
if( ! "".equals(wantedDate) ) {
// everything OK
} else {
// error cannot retrieve date!
}
Related doc:
indexOf : http://developer.android.com/reference/java/lang/String.html#indexOf%28java.lang.String%29
SimpleDateFormat : http://developer.android.com/reference/java/text/SimpleDateFormat.html
you can use a SimepleDateFormat to parse it. For example:
long ts = 1362451303699;
Date date = new Date(ts);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
System.out.println(sdf.format(date));
With the SimpleDateFormat you can bring your Date in a more readable format.
It is a UNIX epoch timestamp, all you need to do is to convert the String representation of the number to long, then you can use it to create a Date object, which you can format with DateFormat. Something like this:
// Get this from the log
String timestamp = "1362451303699";
long epoch = Long.parseLong(timestamp);
Date date = new Date(epoch);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String formattedDate = format.format(date);
I have a problem that I have a timestamp value which is coming from JSON parsing, I am converting that timastamp in Date Time Format which is desired, all is working fine but month always return 1 in any case. means If timestamp contains aug month but it returns only 1 for any month. I don't know how to resolve this. Please suggest me the solution for the same.
Thanks in advance.
Code:
public String create_datestring(String timestring){
try{
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Long.parseLong(timestring));
timestring = String.valueOf(cal.get(Calendar.MONTH)+1) + "/" +String.valueOf(cal.get(Calendar.DAY_OF_MONTH)) + "/" + String.valueOf(cal.get(Calendar.YEAR));
}catch(NumberFormatException e){
timestring = "9/23/2011";--->timestring always returns 1 for month.
}
private String getDate(String timeStampStr){
try{
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date netDate = (new Date(Long.parseLong(timeStampStr)));
return sdf.format(netDate);
}
catch(Exception ex){
return dateInStr;
}
}
Try this one It may gives you satisfied output.
String DATE_FORMAT="hh:mm aa dd MMMM yyyy";
#SuppressLint("SimpleDateFormat")
private String getDate(long time) {
return new SimpleDateFormat(DATE_FORMAT).format(time * 1000);
}