The output in all the samples i've seen is always like
08-16 10:34:13.280 D/MobileDataStateTracker( 886): default: This tracker is connected to sub=0
The date and time displaying without a year,
the format is always MM-dd HH:mm:ss.SSS
Can I change the format to get the year as well?
For now I use a workaround like this:
public static Date addCurrentYearToDate(Date extractDate) {
Calendar instance = Calendar.getInstance();
instance.setTime(extractDate);
instance.add(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR) - instance.get(Calendar.YEAR));
Date actualDate = new Date(instance.getTimeInMillis());
return actualDate;
}
Related
This question already has answers here:
How to format date and time in Android?
(26 answers)
Closed 3 years ago.
I was building an android app and i was using Date class in my project to get the current date. I formatted the date with simpledateformatter and displayed it like dd-mm-yyyy (i.e. day month year) .
Now i also want to get the time in format of hh:MM:ss a (hours minutes seconds AM/PM)
As i was using date's instance i saw that it displays date and time also ( in default format). So i tried to fetch time from the date's instance.(let's say d is date class instance). I also found getTime() method of date class and performed d.getTime() but it returned me a long (which is duration from some fixed time from past to current time). Now i want time in desired format but this getTime() method is giving me long.
May you provide me some way on how to process this long value to get the desired format of time out of it. For example , d.getTime() return me some value( say 11233) and i want in format like this (11:33:22).
You can make that
private final String DATE_FORMAT = "dd.MM.yyyy HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Date got = sdf.parse(date);
It returns Date with time to you
Use this snippet to get the date and time both.
public String currentDateTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss aa"); //it will give you the date in the formate that is given in the image
String datetime = dateformat.format(c.getTime()); // it will give you the date
return datetime;
}
Note: Take a look in the image .
Date().getTime() is providing you the timestamp
Change the format to your requirement like mm:hh:ss a
Kotlin
fun getDateTime():String {
val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
val date = Date()
return inputFormat.format(date.time)
}
JAVA
private String getDateTime(){
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
return format.format(new Date().getTime());
}
This question already has answers here:
Calendar date to yyyy-MM-dd format in java
(11 answers)
Closed 4 years ago.
I am encountering an issue which is related to Java Date Function.
I'm getting the date from Application (example: 6/5/18) which is in MM/DD/YY format. Now I need to do -2 from the date. I know how to do -2 from current system date using calendar object (see the below code).
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
info("Date is displayed as : "+ PastDate );
I'm not able to put the date which I'm getting from Application in this format. Can someone please help me? (Any other way to do it would also be fine)
I suggest you to use Java 8 compatible Date and Time types.
If you use java.time.LocalDate then this is the solution:
LocalDate.now().minusDays(2)
From your question, it seems that you have the challenge in dealing with formatting, and then doing the subtraction.
I would recommend Java Date and Time Apis for this purpose, using a formatter.
A junit method to achieve your requirement is given below
#Test
public void testDateFormatUsingJava8() {
CharSequence inputdateTxt = "6/5/18";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yy");
LocalDate inputDate = LocalDate.parse(inputdateTxt, formatter);
System.out.println(inputDate.minusDays(2L).format(formatter));
}
#Test
public void testDateCalenderUsingStringSplit() {
String inputdateTxt = "6/5/18";
String[] dateComponenets = inputdateTxt.split("//");
Calendar cal = Calendar.getInstance();
//Know where are the year month and date are stored.
cal.set(Integer.parseInt(dateComponenets[2]), Integer.parseInt(dateComponenets[0]), Integer.parseInt(dateComponenets[2]) );
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
}
#Test
public void testDateCalenderUsingJavaUtilDateApi() throws ParseException {
String inputdateTxt = "6/5/18";
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
Date date = dateFormat.parse(inputdateTxt);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE,-2);
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
The reason why I use "M/d/yy" is because your question does not pad the date and month fields in the input date with a zero. If there is a guarantee that you receive a padded value in the date and month field, using "MM/dd/yy" is suggested.
See the following answer for your reference :
DateTimeFormatterSupport for Single Digit Values
EDIT: considering the limitation to not use Java 8 Date Time APIs, I have added two other alternatives to solve the problem. The OP is free to choose any one of the solutions. Kept the Java 8 solution intact for information purposes.
Calendar cal = Calendar.getInstance();
cal.set(2018, 5, 6); // add this, setting data from the value you parsed
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ PastDate);
I am trying to get the CalendarView widget to display only 1 week from current date. I tried using ,
Date date = new Date();
cal = (CalendarView) findViewById(R.id.calendarView1);
cal.setMaxDate(date.getTime()+604800000);
cal.setMinDate(date.getTime());
but it doesn't seem to work. Really appreciate if someone could help me out.
u can set like this here eg. i set the date to 25 -12(december)- current year. You want something like: just get 1 week from current date and u can set like this also
public static Calendar defaultCalendar() {
Calendar currentDate = Calendar.getInstance();
currentDate.set(Calendar.MONTH, 11); // Months are 0-based!
currentDate.set(Calendar.DAY_OF_MONTH, 25); // Clearer than DATE
return currentDate;
}
I'm trying to set the Date Picker of my app with the retrieved date value stored in my database on the OnCreate method. Everything is fine until I come to set the date picker with the year, month and day values themselves. At the moment the date picker is always being set to '01 Jan 1970'. Hopefully someone can point me int the right direction here.
As shown I parse the string to a Date object then retrieve the separate year, month and day values. They're stored as interger, then using the .init method it should set my date picker.
Here's my code so far:
DBHandlerApp dateToEdit= new DBHandlerApp(this, null, null);
dateToEdit.open();
String returnedDate = dateToEdit.getTime(passedID);
SimpleDateFormat newFormatDate = new SimpleDateFormat("dd-MMM-yyyy");
try
{
dateToEditApp = newFormat.parse(returnedDate);
} catch (ParseException e)
{
e.printStackTrace();
}
Calendar calDate = Calendar.getInstance();
calDate.setTime(dateToEditApp);
int year = calDate.get(Calendar.YEAR);
int monthOfYear = calDate.get(Calendar.MONTH);
int dayOfMonth = calDate.get(Calendar.DAY_OF_MONTH);
editDatePicker.init(year, monthOfYear, dayOfMonth, null);
There might be a small issue with your code, i think you misnamed the newFormatDate when trying to parse it, which would goto the default value of the dateToEditApp (which is the 1-1-1970 date)
shouldnt
dateToEditApp = newFormat.parse(returnedDate);
be
dateToEditApp = newFormatDate.parse(returnedDate);
?
the date '01 Jan 1970' is an default value, because it starts counting milliseconds from '01 Jan 1970' till today. So I guess something went wrong, when you acquire your date from the database or while parsing it. Can you check wether the parse throws an exception?
I have a date that I get from a server formatted in EST like this
05/07/2012 16:55:55 goes month/day/year then time
if the phone is not in EST how can I convert it to the timezone the phone is in?
it would be not problem if I got the time in milliseconds but I dont
EDIT:
ok now the time is not correct when formatting
String sTOC = oNewSTMsg.getAttribute("TOC").toString();
String timezoneID = TimeZone.getDefault().getID();
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("EST"));
String newtimezoneID = TimeZone.getDefault().getID();
Date timestamp = null;
try{
timestamp = format.parse(sTOC);
format.setTimeZone(TimeZone.getDefault());
timezoneID = format.format(timestamp);
}catch(ParseException e){
}
I convert it to "EST" then format that time to the default TimeZone but the time is always off by an hour, not sure why?
Use the following code to get a UNIX timestamp:
String serverResp = "05/07/2012 16:55:55";
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
Date date = format.parse(serverResp);
Now you have the timestamp, which you know how to use.
Here's another question which covers conversion, in case you are curious: Android Convert Central Time to Local Time
Use the DateFormat class to parse the String into a Date. See the introduction to the API document here... http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html
You can then create a Calendar for the Date...
Calendar cal = Calendar.getInstance().setTime(date);
And then you can change the timezone on the Calendar to a different timezone using setTimezone(). Or just get the time in milliseconds, using getTimeInMillis()
Using the Calendar, Date, and DateFormat classes should put you in the right direction.
See the Calendar documentation here... http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html