Formatting Long value to Date String? - android

I am working on an application in which I have to convert a long value to a Date string and display. To achieve the purpose I am using following function, but it is returning me the date from 70's and 80's obviously not appropriate. I am using the following finction:
public static String convertDateFromLongToCompleteString(long date) {
Date d = new Date(date * 1000);
SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
String formattedDateFromLong = dateformat.format(d);
return formattedDateFromLong;
}
The long value is just simply System.currentTimeMillis() and when I have to show it to the user, I have to format that for which I am using above function. I have checked system and device dates, their zones and time, everything is just fine. Please update that why is this issue appearing and how can I get the exact date. Thanks!
Edit
I have also tried withoout multiplication with 1000, it gives me time and date from 1970.

If your long date is simply System.currentTimeMillis(), then multiplication with 1000 is not required.
Date d = new Date(date);

Replace Date d = new Date(date * 1000); with Date d = new Date(date);

In case you're using the above method only with System.currentTimeMillis(), you can call Date constructor without any parameters, it will give you the Date object that refers to the current date and time. This will be an easier way to solve your problem. Hope this helps.

Related

Add one day to calendar to make test if-else

I use DateTime values in my app. I can create Lessons, and I have to set the beginning nd the end of that lesson.
Let's say I create like this :
English - Beginning 07.05.2017 End 07.07.2017
Then I want to modify the end of that lesson and put :
07.06.2017
I check to see if the dates are OK, but I'm not sure about what I did, because I dont want to let the user to modifiy or create lessons in the past, but if he creates a lesson that finishes the current day, that's ok.
I wrote like this in my if else :
String date1 = datedebut.getText().toString();
String date2 = datefin.getText().toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date_debutnew = dateFormat.parse(date_initial);
Date date_derniernew = dateFormat.parse(date_derniercours);
Calendar calendar = Calendar.getInstance();
if (date_debutnew.after(date_derniernew) || date_derniernew.before(calendar.getTime()))
{ ... }
How can I add one day to that calendar ?
Thank you for the future hlep.
You can use compareTo() method of Date.
It will return,
a value 0 if the argument Date is equal to this Date;
a value less than 0 if this Date is before the Date argument;
a value greater than 0 if this Date is after the Date argument.
From what I understand of the problem, your new Finish date should be after the new Start date and before the designated end Date.
so, the condition should be :
if (date_derniernew.after(date_debutnew) || date_derniernew.before(date2)) {
..}

Same Milliseconds values coming for different dates

I store my values in database by converting the date value in milliseconds,so to get the latest date on top by using order by desc query. The order is coming as required but if i enter date 02/01/2016 and 01/30/2016 both are storing same milliseconds value.
String date = "02/01/2016";
String month = date.substring(0, 2);
String day = date.substring(3, 5);
String year = date.substring(6, 10);
Calendar c1 = Calendar.getInstance();
c1.set(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
long left = c1.getTimeInMillis();
After debugging i got the following milliseconds values
02/01/2016----61414914600000
and 01/30/2016----61414914600000
Anybody knows why this happening?
Using SimpleDateFormat value I am getting different milliseconds value:
Date date;
String dtStart = "02/01/2016";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
date = format.parse(dtStart);
long timeMills=date.getTime();
System.out.println("Date ->" + date);
} catch (Exception e) {
e.printStackTrace();
}
I ran your initial code and it functions almost as expected. A few points:
You mention millisecond 61414914600000. That's not correct because it's 1900 years into the future:
http://currentmillis.com/?61414914600000
I'm pretty sure you got that number from a Date object, not from a Calendar: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date(int, int, int)
As Mat said the month is zero-based for Calendar and the line where you call the setter should subtract 1:
c1.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
You answered your own question with another snippet of code but Date is deprecated, Calendar should be used instead. Your original code in the initial post was essentially correct (except the zero-based month). You should make sure that you know where your output is coming from and / or that you don't forget to build the code before running it.

Comparing formatted dates

I create a date and then format is like this:
Example 1:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
String currentDate = sdf.format(new Date());
What I would like to do is check if this date is before another date (also formatted the same way). How would I go about doing this?
Example 2:
Also, how would I check whether one of these is before another:
long setForLong = System.currentTimeMillis() + (totalTime*1000);
String display = (String) DateFormat.format("HH:mm:ss dd/MM/yyyy", setForLong);
EDIT:
I think more detail is needed. I create a date in two different ways for two different uses. The first use just formats the current date into a string so it is readable for the user. In the second case, I am using a date in the future with System.currentTimeMillis and adding on a long. Both result in a string.
Both methods format the date in exactly the same way, and I set the strings into a TextView. Later, I need to compare these dates. I do not have the original data/date/etc, only these strings. Becasue they are formatted in the same way, I though it would be easy to compare them.
I have tried the if(String1.compareTo(String2) >0 ) method, but that does not work if the day is changed.
If you only have two String objects that are dates available to you. You will need to process them in something, either in your own comparator class or in another object. In this case, since these are already formatted into dates, you can just create Date objects and compare using the methods previously posted. Something like this:
String string = "05:30:33 15/02/1985";
Date date1 = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.ENGLISH).parse(string);
String string2 = "15:30:33 01/02/1985";
Date date2 = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.ENGLISH).parse(string2);
if(date1.getTime()>date2.getTime()) {
//date1 greater than date2
}
else if(date1.getTime()<date2.getTime()) {
//date1 less than date2
}
else {
//date1 equal to date2
}
You should use Calendar for convenient comparing dates.
Calendar c1 = Calendar.getInstance();
c1.setTime(Date someDate);
Calendar c2 = Calendar.getInstance();
c2.setTime(Date anotherDate);
if(c1.before(c2)){
// do something
}
And you can format it at any time
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
String currentDate = sdf.format(c1.getTime());

How do I print just the milliseconds (time between last second and next second) of a Date object?

I am building a basic logging utility class and would like to log the date and time down to the millisecond of when the log entry is created. I'm currently using:
Date d = new Date();
String dateToOutput = DateFormat.format( "MM-dd hh:mm:ss", d )
which gives me '05-23 09:05:47'. I would like it to give me the milliseconds of when the log entry is created also and it does not appear that the DateFormat class supports millisecond retrieval.
Like the format "MM-dd hh:mm:ss:zzz" giving '05-23 09:05:47.447'.
Is it possible to do this using the DateFormat class (or a class like DateFormat)? I recognize it is possible to create another date removing the milliseconds part of this date and then subtracting the two and printing the difference but that's just silly. (:
Try this
Date d = new Date();
SimpleDateFormat sdf=new SimpleDateFormat("MM-dd hh:mm:ss SSS");
String dateToOutput = sdf.format(d);
While I think it's silly the DateFormat class doesn't allow easy formatted output of milliseconds, I realized that obtaining the milliseconds from the timestamp is actually quite easy. Every date object is representing a timestamp in milliseconds since 00:00 January 1, 1970 so the timestamp modulo 1000 gives the milliseconds.
I did
Date d = new Date();
String dateToOutput = DateFormat.format( "MM-dd hh:mm:ss", d );
dateToOutput += "." + d.getTime() % 1000;
which, while not ideal, works fine and gives me '05-23 09:05:47.447'.

SimpleDateFormat get only the time

I have a problem when I try to get only the time from a Timestamp.
An example of the Timestamp is:
2012-04-19T23:05:00+0200
I think the format is "yyyy-MM-dd'T'HH:mm:ss.SSSZ" right?
And it must be "HH:mm".
I use the following code, but it returnes nothing:
public String getTime(String Vertrektijd){
final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date dateObj;
String newDateStr = null;
try
{
dateObj = df.parse(Vertrektijd);
SimpleDateFormat fd = new SimpleDateFormat("HH:mm");
newDateStr = fd.format(dateObj);
}
catch (Exception e)
{
e.printStackTrace();
}
return newDateStr;
}
Thanks for the help!
Your code is correct...
In the example time what you have given in the question(ie, "2012-04-19T23:05:00+0200") is missing MilliSeconds
Try passing this
getTime("2012-04-19T23:05:00.235+0200");
It should work.
Edit:
As MH mentioned, If you dont want to use milliseconds
you can change the code to
final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date has a getHours() and getMinutes() function, but it is deprecated. The proper way would be to use a Calendar
Calendar calendar = Calendar.getInstance();
calendar.setTime( dateObj );
int hours = calendar.get( Calendar.HOUR_OF_DAY );
int minutes = calendar.get( Calendar.MINUTE );
Here is an attempt to summarize all the confusing classes that Java and Android provide to do with dates, times and timezones. Basically, you do most of your date/time manipulations using GregorianCalendar objects, probably using methods from the Calendar superclass. To do locale-specific formatting, you need a DateFormat. But that can only format Date objects, so you need to convert your Calendar/GregorianCalendar to one of those first. Basically, SimpleDateFormat is for doing custom formatting, as you’ve already discovered.
Note there are two different classes called “DateFormat”.

Categories

Resources