I am downloading some JSON data from a web service. In this JSON i get the Date values like "Date=1423131814.0"
This is the Date/Time on which the image is getting uploaded. Now, I need to get the original Date/Time from above returned number.
and then I also need to display the hour only same as Facebook, like 5 hrs ago, yesterday at 2:30 PM.
/**
* Return date in specified format.
* #param milliSeconds Date in milliseconds
* #param dateFormat Date format
* #return String representing date in specified format
*/
public static String getDate(long milliSeconds, String dateFormat)
{
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
And invoke this method as getDate(millis, "dd/MM/yyyy hh:mm:ss.SSS")
Related
How to convert double to date?
"orderDate":1538398507000,
this is how I'm getting date, and I'm converting it to date
Date d = new Date(myOrderDataList.get(position).getOrderDate()*1000);
but it shows 1970 as a year
Try this
private String getStringDate(long time) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(time);
String date = DateFormat.format("dd-MM-yyyy", cal).toString();
return date;
}
Since your double represents the number of seconds of you date from now, and the Date constructor in Java is expecting a number of milliseconds since 01-01-1970, you have to multiply your number to get a number of milliseconds (* 1000) and substract that from the current number of milliseconds since 01-01-1970 (System.currentTimeMillis()):
double myDouble = -242528463.775282;
long myLong = System.currentTimeMillis() + ((long) (myDouble * 1000));
System.out.println(myLong);
Date itemDate = new Date(myLong);
String myDateStr = new SimpleDateFormat("dd-MM-yyyy").format(itemDate);
System.out.println(myDateStr);
But, the problem with the way you store your dates is that if you are calling this code today and tomorrow it will not return the same date, as the current time is changing. You should use timeIntervalSince1970 instead of timeIntervalSinceNow.
My Application downloading shopping details.
Example :
Shopping details downloaded at 5 :30 London time.
Now, change any other timezone, so convert downloaded time s per the selected timezone.
Timezone is changing from settings under Date/time.
How to programmatically achieve this ?
so how to convert the downloaded time as per the timezone selection ?
Try this,
I assume you have downloaded the shopping details at 12:00 PM London time. I am using HH assuming that you are using 24hr format. If you want to convert that to device default time zone, set the timezone using DateFormat & format the existing time.
TimeZone.getDefault() which gives the device default timezone.
try {
DateFormat utcFormat = new SimpleDateFormat("HH:mm");
utcFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = utcFormat.parse("12:00");
DateFormat deviceFormat = new SimpleDateFormat("HH:mm");
deviceFormat.setTimeZone(TimeZone.getDefault()); //Device timezone
String convertedTime = deviceFormat.format(date);
} catch(Exception e){
}
no, there are no APIs for changing time or timezone.. It is not possible to change the phone's timezone programmatically.
Based on #Raghavendra solution, this can be a portable method as follows:
/**
* converts GMT date and/or time with a certain pattern into Local Device TimeZone
* Example of dateTimePattern:
* "HH:mm",
* "yyyy-MM-dd HH:mm:ss",
* "yyyy-MM-dd HH:mm"
* Ex of dateTimeGMT:
* "12:00",
* "15:23",
* "2019-02-22 09:00:21"
* This assumes 24hr format
*/
#SuppressLint("SimpleDateFormat")
private String getDeviceDateTimeFromGMT(String dateTimePattern, String dateTimeGMT) {
try {
DateFormat utcFormat = new SimpleDateFormat(dateTimePattern);
utcFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // convert from GMT TimeZone
Date date = utcFormat.parse(dateTimeGMT);
DateFormat deviceFormat = new SimpleDateFormat(dateTimePattern);
deviceFormat.setTimeZone(TimeZone.getDefault()); // Device TimeZone
return deviceFormat.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Usage:
getDeviceDateTimeFromGMT("yyyy-MM-dd HH:mm", "2019-02-22 16:07");
getDeviceDateTimeFromGMT("yyyy-MM-dd HH:mm:ss", "2019-02-22 16:07:13");
getDeviceDateTimeFromGMT("H:mm", "16:07");
I have data+time in saved in database (sq lite) in milliseconds, now I want to get data from sq-lite of a specific date and I have date in this format "26-December-2012", how to compare this with milliseconds.
what should be the query to fetch data from database?
You have to convert the milliseconds into date format then compare two dates
convert into date formate
public static String getDate(long milliSeconds, String dateFormat)
{`enter code here`
// Create a DateFormatter object for displaying date in specified format.
DateFormat formatter = new SimpleDateFormat(dateFormat);
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
compare dates
SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = curFormater.parse(date1Str);
Date date2 = curFormater.parse(date2Str);
if (date1.before(date2))
{
}
Simply create a new Calendar with the timeInMilliseconds data from the database.
So, if you have the time in a column called date and the data is in a table called myTable the query to get that is:
select date from myTable ... other constraints
In android, simply use the long value retrieved from the database to construct a new Calendar:
Calendar cal = new Calendar.getInstance();
cal.setTimeInMillis(timeInMsFromDatabase);
Once you have a Calendar object, you can retrieve the values you want with the get(int field) method.
Or, you can use the DateFormat class.
Make sense?
I hope this will be helpful to you
public long getDateLong(String dateString, String format) throws ParseException
{
SimpleDateFormat f = new SimpleDateFormat(format);
Date d = f.parse(dateString);
return d.getTime();
}
//
long timeMillis; // Your long time millis
boolean compare = timeMillis > getDateLong("26-December-2012", "dd-MMMM-yyyy");
how can i insert datetime data in my sqlite database using contentvalues not using raw query?.
datetime('now') insert itself(text) not the time, and can i add addittional hours to the current time?
like, when i press button "1HOUR" it would insert the currenttime + 1 hour in the sqlite database..thanks, kinda confused..
Convert date/time to milliseconds and you get a long. Then you just insert the long value in database.
You can add date/time values together if they are in milliseconds.
--EDITED--
Date myDate = new Date();
long timeMilliseconds = myDate.getTime();
//add 1 hour
timeMilliseconds = timeMilliseconds + 3600 * 1000; //3600 seconds * 1000 milliseconds
//To convert back to Date
Date myDateNew = new Date(timeMilliseconds);
In SQLite the java long value is stored as a int.
You cannot use the datetime functions using the Java wrapper "ContentValues". You can implement in this ways :
1) You can useSQLiteDatabase.execSQL (raw SQL query)
dbObj.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES (null, datetime()) ");
2) You can use SimpleDateFormat
// setting the format to sql date time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
ContentValues initialValues = new ContentValues();
initialValues.put("date_time", dateFormat.format(date));
long recordId = mDb.insert(DB_TABLE_NAME, null, initialValues);
3) you store date value in database as (long type) milliseconds and for displaying you can format it,
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
System.out.println(getDate(82233213123L, "dd/MM/yyyy hh:mm:ss.SSS"));
// Return date in specified format.
// milliSeconds Date in milliseconds
// dateFormat Date format
// return date as string in specified format
public static String formatDate(long milliSeconds, String dateFormat)
{
DateFormat formatter = new SimpleDateFormat(dateFormat);
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
}
1 Second = 1000 Milliseconds, so if you want to add 1 hour then use this formula
currentTImeMilli + (60 * 60 * 1000)
I am using jxl api to read an excel file in android. When I get a date like "30/11/2012" from excel, the LabelCell output shows me date as "11/30/12".
1) I need to get the output in dd/MM/yyyy format when reading the excel file, because it exists that way in excel, so I wouldn't want to unnecessarily convert it into another format. How to do that ?
2) After reading in the excel column's date, I generate 2 variables, one which has excel date - 20 days (lets call it excelMinus20) and another excel date + 10 days (lets call it excelPlus10.
Now, I would like to check going further, if the current system date (smartphone's date) >= excelMinus20 and current system date <= excelPlus10.
How to do this whole thing using java.text.Date ? I tried using joda time as well, but it's too complicated to use. Please guide me at least in the right direction.
Thanks in advance
Omkar Ghaisas
To parse your date from text format:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse("30/11/2012");
More info : SimpleDateFormat doc
To substract days from your date:
public static Date substractDays(Date date, int days)
{
long millis = date.getTime();
long toSubstract = days * 1000 * 60 * 60 * 60 * 24;
// 1milli 1s 1m 1h 1d
return new Date(millis-toSubstract);
}
Adding some days would be the same, except replace - with +
To get back a String representation from a Date object:
DateFormat formatter = new SimpleDateFormat("...pattern...");
String formatedDate = formatter.format(date.getTime());
EDIT:
You could also do the Date adding/substracting with the method you suggested:
public static Date substractDays(Date date, int days)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -20 /*or +10*/);
return calendar.getTime();
}
If you want to check if a Date is in an interval, then:
public static boolean isInInterval(Date date, Date from, Date to)
{
return date.getTime()<to.getTime() && date.getTime() > from.getTime();
}