I want develop TODO-List application with Realm Database, this application user can set Title, Date and time for Task/Todo .
I want when user set Date, hour save to database with 24h instead of am/pm.
for example : i want show hour this formatting 17:34 , but show me 05:34 !
I use this codes, but show me am/pm formatting.
Calendar method and save to database :
// Calendar Method
Calendar calender = Calendar.getInstance();
calender.set(Calendar.DAY_OF_MONTH, dialog_date.getDay()-1);
calender.set(Calendar.MONTH, dialog_date.getMonth()-1);
calender.set(Calendar.YEAR, dialog_date.getYear());
calender.set(Calendar.HOUR, dialog_date.getHour());
calender.set(Calendar.MINUTE, dialog_date.getMinute());
long now = System.currentTimeMillis();
Realm realm = Realm.getDefaultInstance();
Task_Provider task_provider = new Task_Provider(addTask, now, calender.getTimeInMillis(), false);
Code 1 :
private static SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy" + "\n" + " " + "hh:mm");
public void setDate(long when_date) {
card_date.setText(dateFormat.format(new Date(when_date)));
}
}
Code 2 :
private static SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy" + "\n" + " " + "kk:mm");
public void setDate(long when_date) {
card_date.setText(dateFormat.format(new Date(when_date)));
}
}
Code 3 :
private static SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy" + "\n" + " " + "HH:mm");
public void setDate(long when_date) {
card_date.setText(dateFormat.format(new Date(when_date)));
}
}
but this code not work for me!
How can save 24h in calendar method on Android? tnx all <3
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 am trying to convert millisecond time value to UTC 12 hour format using following code:
public void updateDateAndTimeForMumbai(String value) {
SimpleDateFormat outputTimeFormatter = new SimpleDateFormat("h:mm");
SimpleDateFormat outputDateFormatter = new SimpleDateFormat("dd/MM/yyyy");
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
try {
calendar.setTimeInMillis(Long.parseLong(value));
Log.i("Scheduled date: " + outputDateFormatter.format(calendar.getTime()));
Log.i("Scheduled time: " + outputTimeFormatter.format(calendar.getTime()));
Log.i("Scheduled time Am/Pm: " + new SimpleDateFormat("aa").format(calendar.getTime()));
} catch (NumberFormatException n) {
//do nothing and leave all fields as is
}
}
Here value = "1479633900000"
Output is:
Scheduled date: 20/11/2016
Scheduled time: 2:55
Scheduled time Am/Pm: AM
What I want is:
Scheduled date: 20/11/2016
Scheduled time: 9:25
Scheduled time Am/Pm: AM
I don't know where is the problem.
You need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.
outputDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Call this after you do :
SimpleDateFormat outputDateFormatter = new SimpleDateFormat("dd/MM/yyyy");
If the time you are receiving from server is not UTC time, then you shouldn't set your Calendar instance to UTC. but just directly set your Calendar time.
Remove
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
And call
Calendar calendar = Calendar.getInstance();
Here is how should look your final code :
public void updateDateAndTimeForMumbai(String value) {
SimpleDateFormat outputTimeFormatter = new SimpleDateFormat("h:mm");
outputTimeFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat outputDateFormatter = new SimpleDateFormat("dd/MM/yyyy");
outputDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
try {
calendar.setTimeInMillis(Long.parseLong(value));
Log.i("Scheduled date: " + outputDateFormatter.format(calendar.getTime()));
Log.i("Scheduled time: " + outputTimeFormatter.format(calendar.getTime()));
Log.i("Scheduled time Am/Pm: " + new SimpleDateFormat("aa").format(calendar.getTime()));
} catch (NumberFormatException n) {
//do nothing and leave all fields as is
}
}
Good day.I am building an chat application.For purpose i decided to put a date of message had been sent.No wounder that in different countries the date must show different.For example let's take 2 different countries and assume the difference between them are 2 hours.CountryX and CountryY.The user send message from CountryX which time is lets say 15:00.I am saving this on server with exact timezone time as user sent,exactly 15:00 as CountryX.Second user receives the message in CountryY which is more in 2 hours from CountryX,so basically The time which I MUST show in CountryY must be 17:00.This is the issue.How can i convert an already received time with known timezone to local in order to show correct?I did google a lot but all i came up,were solutions where you would simply just get an time for exact country,and not convert the CountryX sent Time to CountryY local time to show it correctly in CountryY.Please can you provide an help?Thank you very much beforehand.
For everyone suffering because of this.I have ended up creating my own class with my own logic and it works flawlessly and as an extra bonus couple of handy methods with time
public class Time {
public static String getCurrentTime() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
String finalFormat = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
if (month < 10) {
String finalMonth = "0" + month;
finalFormat = year + "-" + finalMonth + "-" + day + " " + hour + ":" + minute + ":" + second;
}
return finalFormat;
}
public static String convertToLocalTime(String timeToConvert) {
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getTimeZone(Constants.SERVER_TIME_ZONE));//where server time zone is the time zone of your server as defauul,E.X -America/Los_Angeles
Date parsed;
try {
parsed = sourceFormat.parse(timeToConvert);
} catch (ParseException e) {
e.printStackTrace();
return "";
}
TimeZone tz = TimeZone.getDefault();
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
destFormat.setTimeZone(tz);
String result = destFormat.format(parsed);
return result;
}
public static String getTimeZone() {
return TimeZone.getDefault().getID();
}
}
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 trying to fetch the date 7days prior to today's date.
I am using SimpleDateFormat to fetch today's date.
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
Please guide me through this
Updated answer which I found most useful
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
String currentDateandTime = sdf.format(new Date());
Date cdate=sdf.parse(currentDateandTime);
Calendar now2= Calendar.getInstance();
now2.add(Calendar.DATE, -7);
String beforedate=now2.get(Calendar.DATE)+"/"+(now2.get(Calendar.MONTH) + 1)+"/"+now2.get(Calendar.YEAR);
Date BeforeDate1=sdf.parse(beforedate);
cdate.compareTo(BeforeDate1);
Thank you for you reply
Use java.util.Calendar, set it to today's date and then subtract 7 days.
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DAY_OF_YEAR, -7);
Date 7daysBeforeDate = cal.getTime();
Edit: In Java 8 it can be done much easier by using classes from java.time package:
final LocalDate date = LocalDate.now();
final LocalDate dateMinus7Days = date.minusDays(7);
//Format and display date
final String formattedDate = dateMinus7Days.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(formattedDate);
You can try out this,
import java.util.Calendar;
public class AddDaysToCurrentDate {
public static void main(String[] args) {
//create Calendar instance
Calendar now = Calendar.getInstance();
System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//add days to current date using Calendar.add method
now.add(Calendar.DATE,1);
System.out.println("date after one day : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//substract days from current date using Calendar.add method
now = Calendar.getInstance();
now.add(Calendar.DATE, -10);
System.out.println("date before 10 days : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
}
}
/*
Typical output would be
Current date : 12-25-2007
date after one day : 12-26-2007
date before 10 days : 12-15-2007
*/
Android get date before 7 days (one week)
Date myDate = dateFormat.parse(dateString);
And then either figure out how many milliseconds you need to subtract:
Date newDate = new Date(myDate.getTime() - 604800000L); // 7 * 24 * 60 * 60 * 1000
Or use the API provided by the java.util.Calendar class:
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date newDate = calendar.getTime();
Then, if you need to, convert it back to a String:
and finally
String date = dateFormat.format(newDate);
you can use this kotlin function to get any date before the current date.
/**
* get specific date before current date
* [day] number of day
* [month] number of month
* [year] number of year
* [count] number of day, month, year
*
* return date
*/
fun getBeforeDate(day: Boolean = false, month: Boolean = false, year: Boolean = false, count: Int = 0): String{
val currentCalendar = Calendar.getInstance()
val myFormat = "dd/MM/yyyy" // you can use your own date format
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
if (day){
currentCalendar.add(Calendar.DAY_OF_YEAR, -count)
}else if(month){
currentCalendar.add(Calendar.MONTH, -count)
}else if(year){
currentCalendar.add(Calendar.YEAR, -count)
}else{
// if user not provide any value then give current date
currentCalendar.add(Calendar.DAY_OF_YEAR, 0)
// or you can throw Exception
//throw Exception("Please provide at least one value")
}
return sdf.format(currentCalendar.time)
}
fun getBeforeDate(day: Boolean = false, month: Boolean = false, year: Boolean = false, count: Int = 0): String{
val currentCalendar = Calendar.getInstance()
val myFormat = "dd/MM/yyyy" // you can use your own date format
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
if (day){
currentCalendar.add(Calendar.DAY_OF_YEAR, -count)
}else if(month){
currentCalendar.add(Calendar.MONTH, -count)
}else if(year){
currentCalendar.add(Calendar.YEAR, -count)
}else{
// if user not provide any value then give current date
currentCalendar.add(Calendar.DAY_OF_YEAR, 0)
// or you can throw Exception
//throw Exception("Please provide at least one value")
}
return sdf.format(currentCalendar.time)
}