how to get only the Date without time and GMT? - android

I am trying to get only the date from the Date object but currently i get only the following output:
"Thu Nov 24 17:46:14 GMT +02:00 2016"
and i would like to get:
"24/11/2016"
this is my code:
public String getNextYearDate(){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, 1); // to get previous year add -1
Date nextYear = cal.getTime();
return nextYear.toString();

Just use SimpleDateFormat with dd/MM/yyyy
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
String output = df.format(nextYear);
Documentation

You can try below code :
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, 1);
int mYear = cal.get(Calendar.YEAR);
int mMonth = (cal.get(Calendar.MONTH))+1;
int mDay = cal.get(Calendar.DAY_OF_MONTH);
String result = ""+mDay+"/"+mMonth+"/"+mYear ;

Related

calendar timeinmillis returns wrong value

With a DatePicker I choose a Date and I need the date and the timestamp
from the chosen date:
Calendar calendar = Calendar.getInstance(Locale.GERMANY);
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Ctag = sdf.format(calendar.getTime()).substring(0,3)+".";
CdTag = String.format("%02d",dayOfMonth);
Cmonat = String.format("%02d",monthOfYear+1);
Cjahr = Integer.toString(year);
Cdatum = CdTag+"."+Cmonat+"."+Cjahr;
Ctimestamp = (int) (long) calendar.getTimeInMillis();
getDatum.setText(Ctag+","+CdTag+"."+Cmonat+"."+Cjahr);
Snackbar snackbar = Snackbar.make(cl_main,String.valueOf(Long.valueOf(calendar.getTimeInMillis()).intValue()),3000).setDuration(Snackbar.LENGTH_INDEFINITE);
snackbar.show();
}
};
So I set the date which is picked and calendar.getTimeInMillis() I want the timestamp from the date.
But for example I choose today 18.04.2019 it returns 843974600
and when I convert it on a UNIX convert website it gives me
following date:
GMT: Sunday, 29. September 1996 05:23:20
Your time zone: Sonntag, 29. September 1996 07:23:20 GMT+02:00 DST
Relative: 23 years ago
You can try with this code, it should work :
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);
Long timeinmilli = calendar.getTimeInMillis(); //will give tou time in ms
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); //format of the date, choose what you want
Date resultdate = new Date(timeinmilli); //create an object date associated to the time in ms
String date = DateFormat.format(resultdate).toString(); //convert the date into a string with the format you choose

Date string dose not get parse

I have a string in date format which I want to parse in date object. I want to set the time as string in calendar object and want to set an alert at the same time.
For this I tried to parse the string into date but nothing happens. The time dose not get set.
When I did debug to check if the time get's set in calendar or not, then found that it goes directly at the end of method after the parsing.
Date date = df.parse(alertDateTest);
I tried to parse the string with this format :
SimpleDateFormat df = new SimpleDateFormat("d MMM yyyy");
But it gives invalid format exception. Which format should I use to parse this string?
String format is : d MMM yyyy
code:
mAlertDate is 25 Apr 2016
alertDateTest is 25 Apr 2016
public void updateNotification() {
try {
String alertDateTest = i.getStringExtra("taskAlertDate");
String alertTimeTest = i.getStringExtra("taskAlertTime");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date date = df.parse(alertDateTest);
if (alertDateTest.equals(mAlertDate)) {
String formattedString = date.toString();
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, mHourOfTheDay);
c.set(Calendar.MINUTE, mMinute);
c.set(Calendar.SECOND, 0);
mYear = new DateTime(formattedString).getYear();
mMonth = new DateTime(formattedString).getMonthOfYear();
mDayOfMonth = new DateTime(formattedString).getDayOfMonth();
c.set(Calendar.YEAR, mYear);
c.set(Calendar.MONTH, mMonth);
c.set(Calendar.DAY_OF_MONTH, mDayOfMonth);
date = c.getTime();
Log.d("AlertDate", String.valueOf(date));
Toast.makeText(AddTaskActivity.this, String.valueOf(date), Toast.LENGTH_SHORT).show();
intent = new Intent(AddTaskActivity.this, NotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getBaseContext(), _mId, intent, 0);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
} catch (ParseException e) {
}
}
EDIT:
I have a function onDateSet of date picker in this I have a string format and the string is formatted to the same format:
#Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
// String date = "You picked the following date: "+dayOfMonth+"/"+(++monthOfYear)+"/"+year;
SimpleDateFormat df = new SimpleDateFormat("d MMM yyyy");
mCalendar = Calendar.getInstance();
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
Date date = mCalendar.getTime();
if(DATE_PICKER_TAG == 1)
{
mYear = year;
mMonth = monthOfYear;
mDayOfMonth = dayOfMonth;
mAlertDate = df.format(date);
alertDate.setText(String.valueOf(mAlertDate));
}
if(DATE_PICKER_TAG == 3) {
mDueDate = df.format(date);
dueDate.setText(String.valueOf(mDueDate));
}
}
EDIT: Tried by your answer Umesh Saraswat
String alertDateTest = i.getStringExtra("taskAlertDate");
String alertTimeTest = i.getStringExtra("taskAlertTime");
SimpleDateFormat simpleDateFormate = new SimpleDateFormat("dd MMM yyyy");
Date date = simpleDateFormate.parse(alertDateTest);
// Date date = df.parse(alertDateTest);
if (alertDateTest.equals(mAlertDate)) {
String formattedString = date.toString();
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, mHourOfTheDay);
c.set(Calendar.MINUTE, mMinute);
c.set(Calendar.SECOND, 0);
c.setTime(date);
c.set(Calendar.YEAR, mYear);
c.set(Calendar.MONTH, mMonth);
c.set(Calendar.DAY_OF_MONTH, mDayOfMonth);
date = c.getTime();
The date i got is wed dec 31. String was 26 april 2016. Time did not get set.
Thank you..
To parse Date String with 25 Apr 2016 use dd MMM yyyy string format.
For more information visit, SimpleDateFormat
You can use either "dd MMM yyyy" or "d MMM yyyy"
as I have understood your question,
have a string in date format which I want to parse in date object.
For this first tou need to parse the String date into date formate
SimpleDateFormate simpleDateFormate = new SimpleDateFormate("dd MMM yyyy");
Date date = simpleDateFormate.parse("Your date");
I want to set the time as string in calendar object and want to set an
alert at the same time.
Calendar c = Calendar.getInstance();
calendar.setTime(date)
c.set(Calendar.HOUR_OF_DAY, mHourOfTheDay);
c.set(Calendar.MINUTE, mMinute);
c.set(Calendar.SECOND, 0);
;
If you want to use Calendar object date into a String formate then
SimpleDateFormate simpleDateFormate = new SimpleDateFormate("Your Date format String");
String date = simpleDateFormat.format(c.getTime);
Just added Locale to the format and it worked..
SimpleDateFormat simpleDateFormate = new SimpleDateFormat("dd MMM yyyy",Locale.ENGLISH);
Thank you all..

Date object from simple string - Java and Android [duplicate]

This question already has answers here:
How to get the day, year, hours, min Individually from date format "yyyy-MM-dd'T'HH:mm:ss.SSSZ"?
(4 answers)
Closed 9 years ago.
specific date is "2013-11-12".
I want to extract day, month and year from above date. Please let me know how can I extract?
You can use split().
Example :
String mydate="2013-11-12"; //year-month-day
String myyear=mydate.split("-")[0]; //0th index = 2013
String mymonth=mydate.split("-")[1]; //1st index = 11
String myday=mydate.split("-")[2]; //2nd index = 12
you can use substring method to extract the particular characters from the above string like:
String year=date.substring(0,4); //this will return 2013
String month=date.substring(5,7); //this will return 11
String day=date.substring(8,10); //this will return 12
You can also use Calendar
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2013-11-12"));
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
You can do it using SimpleDateFormat and Calendar Class.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
Now you can use this cal Object to do whatever you want. Not just the date, month or year. you cam use it to perform various operations, such as add month, add year etc...
Create date object from your date string first, like...
String yourDateString = "2013-11-12";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
Date yourDate = parser.parse(yourDateString);
Now create Calender instance to get further information about date...
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourDate);
int months = calendar.get(Calendar.DAY_OF_MONTH);
int seconds = calendar.get(Calendar.SECOND);
// and similarly use calender.getXXX
Hope this helps...
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date testDate = null;
try {
testDate = sdf.parse("2013-11-12");
}
catch(Exception ex) {
ex.printStackTrace();
}
int date= testDate.getDate();
int month = testDate.getMonth();
int year = testDate.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;
}
}

Android SimpleDateFormat and future dates

long time = 1342580400; //This should be GMT: Wed, 18 Jul 2012 03:00:00 GMT
Date date = new Date(time);
SimpleDateFormat dateSdf = new SimpleDateFormat("dd MMM");
String strTime = dateSdf.format(date);
System.out.println(strTime); //This gives me 16 Jan instead.
Any ideas?
If you run the following code:
SimpleDateFormat dateSdf = new SimpleDateFormat("dd MMM yyyy hh:mm:ss Z");
Date d = dateSdf.parse("18 Jul 2012 03:00:00 GMT");
System.out.println(d.getTime());
You will get the output: 1342580400000
So your problem is that you are missing a few numbers.
Date dt = new Date();
// Fri Dec 02 17:23:13 GMT+05:30 2011
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
gmtFormat.format(dt);
Calendar new_c = gmtFormat.getCalendar();
int hours = new_c.get(Calendar.HOUR_OF_DAY);
int minutes = new_c.get(Calendar.MINUTE);
int seconds = new_c.get(Calendar.SECOND);
mYear = new_c.get(Calendar.YEAR);
MMonth = new_c.get(Calendar.MONTH);
mDay = new_c.get(Calendar.DAY_OF_MONTH);
new_c.setTimeZone(tz);
MMonth = MMonth + 1;
String curdate = mDay + "-" + MMonth + "-" + mYear;
It seems your manual calculation of date from time is wrong. I tried the following code :
long currTime = System.currentTimeMillis();
Date date = new Date(currTime);
SimpleDateFormat dateSdf = new SimpleDateFormat("dd MMM");
String strTime = dateSdf.format(date);
System.out.println(strTime);
And it gave me the correct date viz 21 Dec

Categories

Resources