I just want it to be displayed from current time adding 30mins till day ends
Ex-Today time is 09:46AM
It should display like 10:00AM,10:30AM,11:00AM....11:30PM for that particular date.
But here in my code its displaying from 00:00...23:30 for whole day.
Here is my code:
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
int startDate = cal.get(Calendar.DATE);
while (cal.get(Calendar.DATE) == startDate) {
Log.d("time","currenttime"+cal.getTime());
cal.add(Calendar.MINUTE, 30);
}
java.time and ThreeTenABP
Duration interval = Duration.ofMinutes(30);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
ZoneId zone = ZoneId.of("Europe/Podgorica");
ZonedDateTime now = ZonedDateTime.now(zone);
// Start at a whole half hour no earlier than now
ZonedDateTime start = now.truncatedTo(ChronoUnit.HOURS);
while (start.isBefore(now)) {
start = start.plus(interval);
}
// End when a new day begins
ZonedDateTime limit = now.toLocalDate().plusDays(1).atStartOfDay(zone);
// Iterate
ZonedDateTime currentTime = start;
while (currentTime.isBefore(limit)) {
System.out.println(currentTime.format(timeFormatter));
currentTime = currentTime.plus(interval);
}
When I ran the snippet just now, I got the following output:
20:30
21:00
21:30
22:00
22:30
23:00
23:30
Of course substitute your desired time zone where I put Europe/Podgorica.
I used the following imports:
import org.threeten.bp.Duration;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.temporal.ChronoUnit;
Question: Can I use java.time on my Android API level?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on new Android devices (from API level 26) the modern API comes built-in. In this case import from java.time with subpackages (not org.threeten.bp).
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package org.threeten.bp and subpackages.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
ThreeTen Backport project
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java Specification Request (JSR) 310.
Use "HH:mm" for 24 hr format and "hh:mm a" for 12 hr format
Update 1
Below is a full example that displays what you want on a textview:
TextView timeNow = findViewById(R.id.time_now);
Calendar cal, atMidnight;
//SimpleDateFormat df = new SimpleDateFormat("dd/MM/YYYY hh:mm a");
SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
cal = Calendar.getInstance();
atMidnight = Calendar.getInstance();
atMidnight.add(Calendar.DATE, 1);
atMidnight.set(Calendar.HOUR_OF_DAY, 0);
atMidnight.set(Calendar.MINUTE, 0);
atMidnight.set(Calendar.SECOND, 0);
cal.add(Calendar.MINUTE, 30);
String txt = "";
while (cal.getTime().getTime() < atMidnight.getTime().getTime()) {
txt = txt + df.format(cal.getTime()) + "\n";
cal.add(Calendar.MINUTE, 30);
}
timeNow.setText(txt);
Update 2
To round the minutes to the next 30mins, you can do the below:
while (cal.getTime().getTime() < atMidnight.getTime().getTime()) {
int unroundedMinutes = cal.get(Calendar.MINUTE);
int mod = unroundedMinutes % 30;
cal.add(Calendar.MINUTE, 30-mod);
txt = txt + df.format(cal.getTime()) + "\n";
cal.add(Calendar.MINUTE, 30);
}
timeNow.setText(txt);
Related
I want the date in AM/PM format. Examples suggest to use a SimpleDateFormat with a or aa but this is simply not working for me.
First I set the day. Then I set view to visible for start time.
Result is format of Wed May 20 01:00:00 EDT 2020 want something like Wed May 20 01:00:00 AM EDT 2020
This applies to calendar.getTime() in the setStartTime method. The first method is only included because the day selected is linked as a global variable. Problem lies within the second method.
I could probably manually change the final date as string and convert it back but I don't want to add unnecessary complexity. I want to find out why Calendar won't succeed since this should be extremely basic.
In the end my goal is to add the date to firebase. It must be uniform across Android, IOS and Web. Therefore I need the date to be in this exact format.
Here is code:
SimpleDateFormat serviceSETimeFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm aa");
public void setStartDay(View view)
{
Calendar calendar = Calendar.getInstance();
DatePickerDialog picker = new DatePickerDialog(ServiceCreation.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
GregorianCalendar mCal = new GregorianCalendar(year, monthOfYear, dayOfMonth);
Date dateForDisplay = mCal.getTime();
int startHourIndex = getThirdSpaceIndex(dateForDisplay.toString());
//SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
serviceSETimeFormat.setCalendar(mCal);
Date dateFormatted = null;
try{
dateFormatted= serviceSETimeFormat.parse(serviceSETimeFormat.format(mCal.getTime()));
currBaseStartDate=dateFormatted;
}
catch(ParseException p){
Log.wtf("SC","Parse exc34");
}
Log.wtf("SC","Here is orig date: "+dateFormatted);
//Don't show hh/mm/ss (these are held as 0)
startDayView.setText(dateForDisplay.toString().substring(0,startHourIndex));
startEndTimeWrapper.setVisibility(View.VISIBLE);
}
}, calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
long currentTime = new Date().getTime();
picker.getDatePicker().setMinDate(currentTime);
picker.show();
}
public void setStartTime(View view) {
TimePickerDialog mTimePicker = new TimePickerDialog(ServiceCreation.this,
android.R.style.Theme_Holo_Light_Dialog_NoActionBar, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String minuteAsS = Integer.toString(selectedMinute);
if(minuteAsS.length()==1){
minuteAsS="0"+minuteAsS;
}
if(selectedHour==0){
startTimeView.setText((selectedHour+12)+":"+minuteAsS+" AM");
}
else if(selectedHour<12){
startTimeView.setText(selectedHour+":"+minuteAsS+" AM");
}
else if(selectedHour==12){
startTimeView.setText((selectedHour)+":"+minuteAsS+" PM");
}
else{
startTimeView.setText((selectedHour-12)+":"+minuteAsS+" PM");
}
(findViewById(R.id.endTimeWrapper)).setVisibility(View.VISIBLE);
Calendar calendar = new GregorianCalendar();
calendar.setTime(currBaseStartDate);
calendar.set(Calendar.MINUTE, selectedMinute);
Log.wtf("SC","Hour before condition: "+selectedHour);
if(selectedHour>=12){
if(selectedHour!=12){
Log.wtf("SC","Decrementing hour");
selectedHour-=12;
}
Log.wtf("SC","Hour set: "+selectedHour);
calendar.set(Calendar.AM_PM,Calendar.PM);
calendar.set(Calendar.HOUR_OF_DAY,selectedHour);
}
else{
calendar.set(Calendar.AM_PM,Calendar.AM);
calendar.set(Calendar.HOUR_OF_DAY,selectedHour);
}
startTime=calendar.getTime();
Log.wtf("SC","Here is orig start time: "+startTime);
try{
startTime=serviceSETimeFormat.parse(serviceSETimeFormat.format(startTime));
Log.wtf("SC","Here is parsed start time: "+startTime);
}
catch(ParseException e){
Log.wtf("SC","START DATE PARSE EXCEPTION");
}
}
}, 12, 0, false);
mTimePicker.setTitle("Select Start Time: ");
mTimePicker.show();
}
Three points:
Even on Android and even on API levels under 26 consider using java.time, the modern Java date and time API. Calendar, GregorianCalendar, SimpleDateFormat and Date are confusing, poorly designed and long outdated classes. The modern API is so much nicer to work with.
You don’t want a Calendar or Date with AM or PM. You want to keep your model and your presentation to the user separate. In the model you want a LocalDateTime or other appropriate date-time object, and you don’t want to worry about its format, whether it uses a 12 hours or 24 hours clock. For display to your user you want date and time in a string in an appropriate format for you user, including AM or PM. This is also why your views have a setText method and no setDate method.
No Date with AM/PM format can exist. You are asking the impossible.
java.time and ThreeTenABP
Construct a LocalDate object from your three integers for year, month and day:
int year = 2020;
int monthOfYear = Calendar.MAY; // Don’t use Calendar, though
int dayOfMonth = 11;
LocalDate date = LocalDate.of(year, monthOfYear + 1, dayOfMonth);
System.out.println(date);
Output:
2020-05-11
I believe that your date picker numbers months from 0 for January through 11 for December. So we need to add 1 to the month number to convert to the way humans and LocalDate number months. I am only using the constant from the Calendar class to initialize the variable to a 0-based month number, don’t do it in your code since the value comes from the data picker. Calendar uses the same insane numbering.
To display the date back to the user format it into a string using a formatter:
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.US);
String dateForDisplay = date.format(dateFormatter);
System.out.println(dateForDisplay);
May 11, 2020
Give the appropriate locale, or leave out the call to withLocale() to rely on the locale setting of the device.
When the user selects the time:
int selectedHour = 1;
int selectedMinute = 0;
LocalTime selectedTime = LocalTime.of(selectedHour, selectedMinute);
LocalDateTime dateTime = date.atTime(selectedTime);
System.out.println(dateTime);
2020-05-11T01:00
The time can be formatted in a way that is very similar to what we did with the date:
DateTimeFormatter timeFormatter = DateTimeFormatter
.ofLocalizedTime(FormatStyle.MEDIUM)
.withLocale(Locale.US);
String timeForDisplay = selectedTime.format(timeFormatter);
System.out.println(timeForDisplay);
1:00:00 AM
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
My thorougher answer to a similar question: want current date and time in “dd/MM/yyyy HH:mm:ss.SS” format
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
I want to make a Calendar according to Timezone. I tried to resolve the issue by surfing different queries but i can't. Now it pick mobile default time. If anyone have idea please help me. Timezone should be UK time.
I tried:
{
Calendar c1;
c1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
int hour = c1.get(Calendar.HOUR);
int minutes = c1.get(Calendar.MINUTE);
int seconds = c1.get(Calendar.SECOND);
int day = c1.get(Calendar.DAY_OF_MONTH);
int month = c1.get(Calendar.MONTH);
int year = c1.get(Calendar.YEAR);
}
But it also returns System date.
java.time
ZonedDateTime nowInUk = ZonedDateTime.now(ZoneId.of("Europe/London"));
int hour = nowInUk.getHour();
int minutes = nowInUk.getMinute();
int seconds = nowInUk.getSecond();
int day = nowInUk.getDayOfMonth();
Month month = nowInUk.getMonth();
int year = nowInUk.getYear();
System.out.println("hour = " + hour + ", minutes = " + minutes + ", seconds = " + seconds
+ ", day = " + day + ", month = " + month + ", year = " + year);
When I ran this snippet just now, it printed:
hour = 3, minutes = 41, seconds = 15, day = 5, month = OCTOBER, year =
2018
ZonedDateTime largely replaces the outdated Calendar class.
What went wrong in your code?
Time zone ID for UK time is Europe/London. In your code you used UTC, which is something else and wll give you a different result, at least sometimes. UK time coincides with UTC some of the year in some years, but not at this time of year this year. So you got a time that was one hour earlier than UK time.
Also c1.get(Calendar.HOUR) gives you the hour within AM or PM from 1 through 12, which I don’t think was what you intended.
Question: Can I use java.time on Android?
Yes, java.time works nicely on Android devices. It just requires at least Java 6.
In Java 8 and later and on new Android devices (from API level 26, I’m told) the new API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package org.threeten.bp and subpackages.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
ThreeTen Backport project
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java Specification Request (JSR) 310.
Use this method for get time from timezone but here is one condition must need to checked auto time in setting's otherwise move to setting's page.
private void setDateTime() {
// Settings.Global.putInt(getContentResolver(), Settings.Global.AUTO_TIME, 1);
try {
int value = Settings.Global.getInt(getContentResolver(), Settings.Global.AUTO_TIME);
if (value == 1) {
Log.i("value", String.valueOf(value));
{
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
String pattern = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, new Locale("en", "in"));
String date = simpleDateFormat.format(new Date());
Log.i("get C_d_t", date);
txt_time.setText(date);
}
} else {
//move to settings
Toast.makeText(getBaseContext(), "Must need to checked automatic date & time", Toast.LENGTH_SHORT).show();
startActivityForResult(new Intent(android.provider.Settings.ACTION_DATE_SETTINGS), 0);
}
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
}
There are many questions like this on StackOverflow but no one has the answer I need. I have seen these 3 questions:
Get Value Of Day Month form Date Object in Android?
How to get month and day in android?
Get current time and date on Android
From these 3 questions I have learnt that to get date and time, we need to use Calendar. I have visited its documentation page but that is too hard to understand.
Now my question is I want to get current day i.e 12, current month i.e November, current year i.e 2014 and hour, minute, not seconds and AM or PM.
I only know till here:
Calendar c = Calendar.getInstance();
Now what should I do next?
You can customize the format you want using
DateFormat df = new SimpleDateFormat("dd MM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
Calendar calander = Calendar.getInstance();
cDay = calander.get(Calendar.DAY_OF_MONTH);
cMonth = calander.get(Calendar.MONTH) + 1;
cYear = calander.get(Calendar.YEAR);
selectedMonth = "" + cMonth;
selectedYear = "" + cYear;
cHour = calander.get(Calendar.HOUR);
cMinute = calander.get(Calendar.MINUTE);
cSecond = calander.get(Calendar.SECOND);
Use SimpleDateFormat to get date and time in desired format :
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd,MMMM,YYYY hh,mm,a");
String strDate = sdf.format(c.getTime());
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
Date currentTime = localCalendar.getTime();
int currentDay = localCalendar.get(Calendar.DATE);
int currentMonth = localCalendar.get(Calendar.MONTH) + 1;
int currentYear = localCalendar.get(Calendar.YEAR);
int currentDayOfWeek = localCalendar.get(Calendar.DAY_OF_WEEK);
int currentDayOfMonth = localCalendar.get(Calendar.DAY_OF_MONTH);
int CurrentDayOfYear = localCalendar.get(Calendar.DAY_OF_YEAR);
System.out.println("Current Date and time details in local timezone");
System.out.println("Current Date: " + currentTime);
System.out.println("Current Day: " + currentDay);
System.out.println("Current Month: " + currentMonth);
System.out.println("Current Year: " + currentYear);
System.out.println("Current Day of Week: " + currentDayOfWeek);
System.out.println("Current Day of Month: " + currentDayOfMonth);
System.out.println("Current Day of Year: " + CurrentDayOfYear);
tl;dr
I want to get current day i.e 12, current month i.e November, current year i.e 2014 and hour, minute, not seconds and AM or PM.
ZonedDateTime
.now(
ZoneId.of( "Pacific/Auckland" ) // Or "Asia/India", "Africa/Tunis", etc.
)
.format(
DateTimeFormatter
.ofPattern(
"dd MMMM uuuu HH:mm"
)
.withLocale(
Locale.CANADA_FRENCH // Or `Locale.US`, or `new Locale( "en" , "IN" )` for English language with India culture.
)
)
See this code run live at IdeOne.com.
28 septembre 2019 08:48
java.time
From these 3 questions I have learnt that to get date and time, we need to use Calendar.
Nope.
The Calendar class is terrible, along with Date & SimpleDateFormat and such. These classes were all supplanted years ago by the modern java.time classes defined in JSR 310.
Now my question is I want to get current day i.e 12, current month i.e November, current year i.e 2014 and hour, minute, not seconds and AM or PM.
Determining a date and time-of-day requires a time zone. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If you want to depend on the JVM’s current default time zone, make your intention clear by calling ZoneId.systemDefault(). If critical, confirm the zone with your user.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
Capture the current moment as seen in the wall-clock time used by the people of a certain region (a time zone).
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
If you do not care about the seconds or fractional-second, truncate.
ZonedDateTime zdt = ZonedDateTime.now( z ).truncatedTo( ChronoUnit.MINUTES ) ;
Generate a string in standard ISO 8601 format, wisely extended to append the name of the time zone in square brackets.
String output = zdt.toString() ;
2019-09-28T01:42+05:30[Asia/Kolkata]
Generate a string, automatically localized.
Locale locale = new Locale( "en" , "IN" ) ; // English language, India culture.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG ).withLocale( locale ) ;
String output2 = zdt.format( f ) ;
28 September 2019 at 1:42:00 AM IST
See this code run live at IdeOne.com.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
public class XYZ extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
Calendar c = Calendar.getInstance();
System.out.println("Current time => "+c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
// formattedDate have current date/time
Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
// Now we display formattedDate value in TextView
TextView txtView = new TextView(this);
txtView.setText("Current Date and Time : "+formattedDate);
txtView.setGravity(Gravity.CENTER);
txtView.setTextSize(20);
setContentView(txtView);
}
}
Calendar calander = Calendar.getInstance();
cDay = calander.get(Calendar.DAY_OF_MONTH);
cMonth = calander.get(Calendar.MONTH) + 1;
cYear = calander.get(Calendar.YEAR);
selectedMonth = "" + cMonth;
selectedYear = "" + cYear;
cHour = calander.get(Calendar.HOUR);
cMinute = calander.get(Calendar.MINUTE);
cSecond = calander.get(Calendar.SECOND);
I have time in milliseconds, now I want to separate time and date from these milliseconds.
how can i do this???
you can use like this
Calendar cl = Calendar.getInstance();
cl.setTimeInMillis(milliseconds); //here your time in miliseconds
String date = "" + cl.get(Calendar.DAY_OF_MONTH) + ":" + cl.get(Calendar.MONTH) + ":" + cl.get(Calendar.YEAR);
String time = "" + cl.get(Calendar.HOUR_OF_DAY) + ":" + cl.get(Calendar.MINUTE) + ":" + cl.get(Calendar.SECOND);
This function will give you a String date from milliseconds
public static String getFormattedDateFromTimestamp(long timestampInMilliSeconds)
{
Date date = new Date();
date.setTime(timestampInMilliSeconds);
String formattedDate=new SimpleDateFormat("MMM d, yyyy").format(date);
return formattedDate;
}
Convert the milliseconds to Date instance and pass it to the chosen formatter:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String myDate = dateFormat.format(new Date(dateInMillis)));
Use a Calendar to get the values of different time fields:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeInMillis);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int monthOfYear = cal.get(Calendar.MONTH);
You could convert the milliseconds to a date object and then extract date in the format of a time string and another string of just the date
Further to Kiran Kumar Answer
public static String getFormattedDateFromTimestamp(long timestampInMilliSeconds, String dateStyle){
Date date = new Date();
date.setTime(timestampInMilliSeconds);
String formattedDate=new SimpleDateFormat(dateStyle).format(date);
return formattedDate;
}
java.time and ThreeTenABP
I suggest java.time, the modern Java date and time API, for your date and time work:
long millisecondsSinceEpoch = 1_567_890_123_456L;
ZonedDateTime dateTime = Instant.ofEpochMilli(millisecondsSinceEpoch)
.atZone(ZoneId.systemDefault());
LocalDate date = dateTime.toLocalDate();
LocalTime time = dateTime.toLocalTime();
System.out.println("Date: " + date);
System.out.println("Time: " + time);
Output in my time zone (Europe/Copenhagen):
Date: 2019-09-07
Time: 23:02:03.456
The date and time classes used in the other answers — Calendar, Date and SimpleDateFormat — are poorly designed and long outdated. This is why I don’t recommend using any of them but prefer java.time.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
You can use the Date format and set your millisecond value as a parameter to this constructor, Follow this code:
SimpleDateFormat SDF= new SimpleDateFormat("dd/MM/yyyy");
String date = SDF.format(new Date(millies)));
I've tried different methods around the web but couldn't make it work.
Cursor cursor = sqlite.myDataBase.rawQuery("SELECT StartDate, EndDate FROM Tracks Where Id="+'"'+trackId+'"',null);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = outputFormat.parse(cursor.getString(cursor.getColumnIndex("StartDate")));
Date endDate = outputFormat.parse(cursor.getString(cursor.getColumnIndex("EndDate")));
In this way I get both dates in good format. Now I want to find the difference between EndDate and Startdate in seconds.
Any advice? Thank you.
You can turn a date object into a long (milliseconds since Jan 1, 1970), and then use TimeUnit to get the number of seconds:
long diffInMs = endDate.getTime() - startDate.getTime();
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);
Edit:
-Corrected the name of the variable diffInMs which was written diffInM(i)s in the second line.
try below method:-
public String twoDatesBetweenTime(String oldtime)
{
// TODO Auto-generated method stub
int day = 0;
int hh = 0;
int mm = 0;
try
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date oldDate = dateFormat.parse(oldtime);
Date cDate = new Date();
Long timeDiff = cDate.getTime() - oldDate.getTime();
day = (int) TimeUnit.MILLISECONDS.toDays(timeDiff);
hh = (int) (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day));
mm = (int) (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
}
catch (ParseException e)
{
e.printStackTrace();
}
if(day==0)
{
return hh + " hour " + mm + " min";
}
else if(hh==0)
{
return mm + " min";
}
else
{
return day + " days " + hh + " hour " + mm + " min";
}
}
Just complementing this answer for other developers (like me) who are using Time instead of Date.
Time t1 = new Time();
t1.setToNow();
Thread.sleep(1000);
Time t2 = new Time();
t2.setToNow();
diff = TimeUnit.MILLISECONDS.toSeconds(t2.toMillis(true)-t1.toMillis(true));
While the other answers work and were fine answers in 2010, I am providing the modern answer.
java.time and ThreeTenABP
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
ZoneId zone = ZoneId.systemDefault();
String startDateString = "2019-12-31 23:34:45";
String endDateString = "2020-01-01 07:56:34";
ZonedDateTime start = LocalDateTime.parse(startDateString, formatter).atZone(zone);
ZonedDateTime end = LocalDateTime.parse(endDateString, formatter).atZone(zone);
long diffSeconds = ChronoUnit.SECONDS.between(start, end);
System.out.println("Difference: " + diffSeconds + " seconds");
In most time zones output from this snippet will be:
Difference: 30109 seconds
I am using ZonedDateTime because it takes transitions to and from summer time (DST) and other time anomalies into account. It requires that you use the correct time zone, of course. If the time zone setting of your device is changed since you stored the dates and times into your database, you risk some surprises. To prevent such, you may store a UTC offset along with your times and then parse them into OffsetDateTime on retrieval.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.