Date and time format in Android - android

How do you format correctly according to the device configuration a date and time when having year, month, day, hour and minute? for example I want to display 29 July, 2015, 10:30 Am, according to my time zone

You can use this method to format the datetime... u can replace new java.util.Date() with any datetime variable...
android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("dd-MMM-yyyy hh:mm aa", new java.util.Date());

String strDateTime = "29 July, 2015, 10:30 Am";
SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM, yyyy, hh:mm a");
strDateTime = sdf.format(Calendar.getInstance().getTime());
holder.txtTime.setText(strDateTime);
Please integrate the above code, that works fine for me.
Any help, do let me know.

Please Find the below solution
Calendar ci = Calendar.getInstance();
String AM_PM;
if(ci.get(Calendar.AM_PM)==0)
{
AM_PM ="AM";
}
else
{
AM_PM ="PM";
}
String CiDateTime = "" + ci.get(Calendar.DAY_OF_MONTH)+" "+
(ci.get(Calendar.MONTH) + 1)+","+
ci.get(Calendar.YEAR) + "-" +
+ "," +getCurrentTime()
+" "+AM_PM;
Call the method
private String getCurrentTime()
{
int hrsRight = 0;
Calendar c = Calendar.getInstance();
int hrs = c.get(Calendar.HOUR);
int min = c.get(Calendar.MINUTE);
if (hrs>12)
{
hrsRight = hrs - 12;
}
else
{
hrsRight = hrs;
}
return String.valueOf(hrsRight)+":"+String.valueOf(min);
}

Related

Calendar.getInstance() returns 1-2-5(Day-Month-Year)

I have this chunk of code:
Calendar date1 = Calendar.getInstance();
DateTime dateTime1 = new DateTime(date1.YEAR, date1.MONTH, date1.DAY_OF_MONTH, date1.HOUR_OF_DAY, date1.MINUTE, date1.SECOND);
My problem is that date1 returns the date 01/02/0005 (in a 1/2/5 format). I read about SimpleDateFormat, however it returns the same value.
date1.YEAR returns only a constant value. The same value as Calendar.YEAR.
Instead, you need to use the date1.get(...) method, in conjunction with Calendar.YEAR. See this example:
Calendar date1 = Calendar.getInstance();
DateTime dateTime1 = new DateTime(date1.get(Calendar.YEAR), date1.get(Calendar.MONTH), date1.get(Calendar.DAY_OF_MONTH), date1.get(Calendar.HOUR_OF_DAY), date1.get(Calendar.MINUTE), date1.get(Calendar.SECOND);
Try these lines of code to get the correct date:-
Calendar ci = Calendar.getInstance();
String AM_PM;
if(ci.get(Calendar.AM_PM)==0)
{
AM_PM ="AM";
}
else
{
AM_PM ="PM";
}
String CiDateTime = "" + ci.get(Calendar.YEAR) + "-" +
(ci.get(Calendar.MONTH) + 1) + "-" +
ci.get(Calendar.DAY_OF_MONTH)+" "+AM_PM;
System.out.println("time=========================================="+CiDateTime);
For yours solution, try these
Calendar ci = Calendar.getInstance();
DateTime dateTime1 = new DateTime(ci.get(Calendar.YEAR), ci.get(Calendar.MONTH), ci.get(Calendar.DAY_OF_MONTH), ci.get(Calendar.HOUR_OF_DAY), ci.get(Calendar.MINUTE), ci.get(Calendar.SECOND);
Try below code:
Calendar date1 = Calendar.getInstance();
Date date = new Date();
date1.setTime(date);
DateTime dateTime1 = new DateTime(date1.YEAR, date1.MONTH, date1.DAY_OF_MONTH, date1.HOUR_OF_DAY, date1.MINUTE, date1.SECOND);

Issue in convert calendar object to date android

I want to convert calendar object to date as follow.
int year,month,day;
mCalendarEnd = Calendar.getInstance();
year = mCalendarEnd.get(Calendar.YEAR);
month = mCalendarEnd.get(Calendar.MONTH)+1;
day = mCalendarEnd.get(Calendar.DAY_OF_MONTH);
Now convert it to date object
Date d1 = new Date(day,month,year);
when I print date object:
System.out.println("Date : "+d1.getDay()+"/"+d1.getMonth()+"/"+d1.getYear());
it should print current date but in above code it prints the wrong date. Any idea how can I solve this problem? your all suggestion are appreciable.
You need to do it like this
//Set calendar
Calendar calendar = Calendar.getInstance();
Date date1 = calendar.getTime(); // gives a date object
//To get day difference, Just an example
calendar.add(Calendar.DAY_OF_MONTH, -7);
Date date2 = calendar.getTime(); // gives a date object
long differenceInMillis = Date1.getTime() - Date2.getTime();
long differenceInDays = TimeUnit.DAYS.convert(differenceInMillis, TimeUnit.MILLISECONDS);
Or No need of date objects
Calendar calendar = Calendar.getInstance();
long date1InMillis = calendar.getTimeInMillis();
calendar.add(Calendar.DAY_OF_MONTH, -7);
long date2InMillis = calendar.getTimeInMillis();
long differenceInMillis = date1InMillis - date2InMillis;
long differenceInDays = TimeUnit.DAYS.convert(differenceInMillis, TimeUnit.MILLISECONDS);
calendar.getTimeInMillis()
calendar.getTime() returns Date object.
but if you just need today date new Date() returns today date as Date object, too.
Calendar example:
Calendar calendar = Calendar.getInstance()
Log.i("My Tag", "calendar getTime -----> " + calendar.getTime());
Output:
My Tag: calendar getTime -----> Wed Dec 05 13:03:43 GMT+03:30 2018
Date Example:
Log.i("My Tag", "new Date -----> " + new Date());
Output:
My Tag: new Date -----> Wed Dec 05 13:05:38 GMT+03:30 2018
as you see both of them have the same output.
Why you don't use just the calendar?
System.out.println("Date : " + day + "/" + month + "/" + year);
result 1/1/1900
or you want other format? but dont increment the month with 1
System.out.println("Date : " + day + "/" + new DateFormatSymbols().getMonths()[month] + "/" + year);
result 1/January/1900
Put this in your code:
Date d1 = new Date(year, month, day);
System.out.println("Date : " + d1.getDate() + "/" +d1.getMonth() + "/" + d1.getYear());
you will get the correct date.
d1=new Date(year, month, day);
System.out.println("Dt:"+d1.getDate()+"/"+d1.getMonth()+"/"+d1.getYear());

To get Date and time from Timestamp Android

I want to get time and date separately from timestamp.Please help me in these. My example of timestamp is 1378798459.
Thanks
//Try the following
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(Long.parseLong(YOUR TIMESTAMP VALUE)));
txtDate.setText(dateString);
//You can put your needed format here:
SimpleDateFormat formatter = new SimpleDateFormat("YOUR REQUIRED FORMAT");
Try this is working with me
public String getDateCurrentTimeZone(long timestamp) {
try{
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.setTimeInMillis(timestamp * 1000);
calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currenTimeZone = (Date) calendar.getTime();
return sdf.format(currenTimeZone);
}catch (Exception e) {
}
return "";
}
Improving upon the answer given by Pratik Dasa
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Here you can get various formats using the following syntax. You can play around with it by deleting or adding terms given below in the syntax.
Date and Time Pattern Result
----------------------------- ---------------------------------
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3
String time = DateUtils.formatDateTime(this, 1378798459, DateUtils.FORMAT_SHOW_TIME);
String date = DateUtils.formatDateTime(this, 1378798459, DateUtils.FORMAT_SHOW_DATE);
Try this,
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
Date date = cal.getTime();
mHour = date.getHours();
mMinute = date.getMinutes();
Only that:
long timestampString = Long.parseLong("yourString");
String value = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").
format(new java.util.Date(timestampString * 1000));
long dv = Long.valueOf(timestamp_in_string)*1000;// its need to be in milisecond
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma").format(df);
From here.
you can use this
Long tsLong = System.currentTimeMillis();
String ts = tsLong.toString();
long millisecond = Long.parseLong(ts);
datetimeString = DateFormat.format("MM-dd-yyyy hh:mm:ss a", new Date(millisecond)).toString();
timeString = datetimeString.substring(11);
dateString = datetimeString.substring(0,10);
String t2 = datetimeString.substring(20,21);
The datetimeString contains the Date Time AM/PM data
timeString will give you the substring which contains the time only and the dateString is substring for date
The String t2 will give you whether it is AM or PM in the clock
int day, month, year;
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
day = date.get(Calendar.DAY_OF_MONTH);
month = date.get(Calendar.MONTH);
year = date.get(Calendar.YEAR);
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
String data =(hour+ ':'+ ""+minute+ ':'+"" +second+"" +""+"" +day+"" +"/" +(month+1)+"" +"/"+ +year);
Toast.makeText(getActivity(), "Time stamp:"+data,Toast.LENGTH_LONG).show();
DateFormat dateFormat = DateFormat.getDateTimeInstance();
when.setText(dateFormat.format(new Date(timestamp * 1000)));
The timestamp is multiplied by 1000 for converting the seconds into milliseconds.
All the answers are great and they mainly focus on converting the unix timestamp to milliseconds first, which is correct.
I struggled to apply that because I must use 1000L in the conversion (instead of 1000 only). Here's my working code with time zone conversion
// Set TimeZone
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yy h:mm a", Locale.US);
dateFormat.setTimeZone(getDeviceTimeZone());
// Set time
Date date = new Date(timestamp * 1000L);
return dateFormat.format(date);
For Android API 26 and above, you can just do
return Instant.ofEpochSecond( timestamp )
.atZone(ZoneId.of( timezone ))
.toLocalDateTime()
.toString();
The very best way to get day and date from the timestamp is that:
java.util.Date dayAndDate = new java.util.Date( (long) yourTimeStamp * 1000);
// object coming as like: Tue Feb 09
String day = dayAndDate.toString().split(" ")[0];
String month = dayAndDate.toString().split(" ")[1];
String date = dayAndDate.toString().split(" ")[2];
I hope you will like my approach, if you have liked it, don't forget to give it an upvote, so that others will consider it.
If you want to use time like in a WhatsApp message, You can use this method,
public static String millisToDateChat(long time) {
long currentTime = System.currentTimeMillis();
long defe = currentTime - time;
long time_in;
if(time!=0){
time_in = time;
}else{
time_in = currentTime;
defe = 0;
}
int s = (int)defe/1000;
int m = (int)defe/(1000*60);
int h = (int)defe/(1000*60*60);
int d = (int)defe/(1000*60*60*24);
int w = (int)defe/(1000*60*60*24*7);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time_in);
Date date = calendar.getTime();
#SuppressLint("SimpleDateFormat") String formattedDate=(new SimpleDateFormat("HH:mm")).format(date);
#SuppressLint("SimpleDateFormat") String formattedYear=(new SimpleDateFormat("MMM d, ''yy")).format(date);
#SuppressLint("SimpleDateFormat") String formattedm=(new SimpleDateFormat("MMM d")).format(date);
if(d>365) {
return formattedYear;
}else if(s>172000){
return formattedm;
}else if(s>86400) {
return "Yest.";
}else{
return formattedDate;
}
}

How can I change date from 24-hours format to 12-hours format (am/pm) in android

Calendar ci = Calendar.getInstance();
CiDateTime = "" + (ci.get(Calendar.MONTH) + 1) +
"/" + ci.get(Calendar.DAY_OF_MONTH) +
"/" + ci.get(Calendar.YEAR);
String visitdatetime = CiDateTime + "" +
ci.get(Calendar.HOUR_OF_DAY) + ":" +
ci.get(Calendar.MINUTE) + ":" +
ci.get(Calendar.SECOND);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
I am getting from the server in 24 hours format.but want to show my date like MM/dd/yyyy hh:mm AM/PM like 12 hrs format.
Did you try this ?
SimpleDateFormat dateFromat= new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
Date today = new Date();
String todayStr = dateFromat.format(today);
Below function may be useful to you. This will convert time from 24 hours to 12 hours
public static String Convert24to12(String time)
{
String convertedTime ="";
try {
SimpleDateFormat displayFormat = new SimpleDateFormat("hh:mm a");
SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm:ss");
Date date = parseFormat.parse(time);
convertedTime=displayFormat.format(date);
System.out.println("convertedTime : "+convertedTime);
} catch (final ParseException e) {
e.printStackTrace();
}
return convertedTime;
//Output will be 10:23 PM
}
public static final String TIME_FORMAT = "hh:mm aa";
SimpleDateFormat TimeFormat = new SimpleDateFormat(TIME_FORMAT);
Calendar ATime = Calendar.getInstance();
String Timein12hourFormat = TimeFormat.format(ATime.getTime());
try with this answer this is shortest and best answer on stack.
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa");
Datetime = sdf.format(c.getTime());
System.out.println("============="+Datetime);
Result:-=========2015-11-20 05:52:25 PM
Here is the answer to get a data in US-English Format date/time using a 12 hour clock.
DateTime.Now.ToString("MM/d/yyyy hh:mm:ss tt");
01/16/2014 03:53:57 PM
hh:mm a
Adding the 'a' should do the trick in displaying the am/pm
In angular i am using angular-bootsrap-datetimepicker and to display the selected date and time i am using this syntax
data-ng-model="event.start | date:'dd-MM-yyyy hh:mm a'"
use below format to 12 hour with am/pm
MM/dd/yyyy HH:mm:ss a

Need get Time in a 24 hour format while adding Time

I had written a function for Adding time as given below
private void Delay15Minute() {
String pkManifest = manifest.pkManifestNo;
manifest_helper = new manifest_helper(this);
cursor = manifest_helper.GetDeliveries(pkManifest);
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.getString(cursor.getColumnIndex("PKDelivery"));
// String
// RevisedTime=cursor.getString(cursor.getColumnIndex("RevisedEstimatedDeliveryTime"));
String RevisedTime = "12:55";
// get hour and minute from time string
StringTokenizer st1 = new StringTokenizer(RevisedTime, ":");
int j = 0;
int[] val = new int[st1.countTokens()];
// iterate through tokens
while (st1.hasMoreTokens()) {
val[j] = Integer.parseInt(st1.nextToken());
j++;
}
// call time add method with current hour, minute and minutesToAdd,
// return added time as a string
String date = addTime(val[0], val[1], 15);
// Tioast the new time
Toast.makeText(this, "date is =" + date, Toast.LENGTH_SHORT).show();
}
}
public String addTime(int hour, int minute, int minutesToAdd) {
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
calendar.add(Calendar.MINUTE, minutesToAdd);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String date = sdf.format(calendar.getTime());
return date;
}
I am getting the oupt of this as 01:10 as 12 hours fromat...
I need to get it in 13:10 format ie 24 hour format.....Please help me
You used hh in your SimpleDateFormat pattern. Thats the 12 hour format. Use kk instead, that gives you the hours of the day in a 24 hour format. See SimpleDateFormat.
Simply create the instance of Calendar and get 24 hr time by,
Calendar c = Calendar.getInstance();
int Hr24=c.get(Calendar.HOUR_OF_DAY);
int Min=c.get(Calendar.MINUTE);
Use this code
long date = System.currentTimeMillis();
SimpleDateFormat date1 = new SimpleDateFormat("dd-MM-yyyy"); // for current date
SimpleDateFormat time1 = new SimpleDateFormat("kk:mm:ss"); // for 24 hour time
SimpleDateFormat time2 = new SimpleDateFormat("hh:mm:ss"); // for 12 hour time
String dateString = date1.format(date); //This will return current date in 31-12-2018 format
String timeString1 = time1.format(date); //This will return current time in 24 Hour format
String timeString2 = time2.format(date); //This will return current time in 12 Hour format
Log.e("TAG_1", "24 hour Time - " + timeString1);
Log.e("TAG_1", "24 hour Time - " + timeString1);
Log.e("TAG_1", "dd-MM-yyyy Date format - " + dateString);
than open your logcat to check result.

Categories

Resources