I've a problem when displaying the date. I do everything fine, the date shows...bad it's not correct!
It says 2012/07/30 when it should be 2012/08/30.
I've checked my date in the mobile and it's correct. Do you have any idea?
Thank you!!
Piece of code:
Calendar c = Calendar.getInstance();
String sDate = c.get(Calendar.DAY_OF_MONTH) + "/" + c.get(Calendar.MONTH) + "/" + c.get(Calendar.YEAR);
view2.setText("" + et.getText() + sDate );
why don't you use DateFormat
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
view2.setText(dateFormat.format(c.getTime());
The Calendar object does not work as you are expecting it. The get(Calendar.MONTH) returns a constant representing the month of the date, not the number of the month. This subtle difference can be seen here:
java.util.calendar
As you will see, the constants reflect a zero-based sequence, starting with January, so that you can use the constants as indexers into an array for month-based lookups.
For your purposes, you could get away with adding 1 to the returned int, but you might want to look at SimpleDateFormat in the java.text. This article provides a brief overview to get you started.
Good luck!
You can instead use this,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String currentDateandTime = sdf.format(new Date())
Related
I am working on a App in which i want to display notification time.
I can display notification time but not able to add time zone in it.
My current location is Pakistan and i want to add GMT+5:00
My code is attached
String currentDateTimeString = DateFormat.getTimeInstance().format(notif.At);
textViewTime.setText(currentDateTimeString);
in this code, notif.At is dateTime variable. I also attached screenshot of my app, i want to ask you , how to add timeZone value in notif.At. Thanks!
Update
You mark time with timezone in order to solve internationalization problem, I understand, right?
If so, I think it could be better to convert your date to UTC date. When you change to another timezone, just convert this UTC Date to local.
public static Date localToUtc(Date localDate) {
return new Date(localDate.getTime()-TimeZone.getDefault().getOffset(localDate.getTime()));
}
public static Date utcToLocal(Date utcDate) {
return new Date(utcDate.getTime()+TimeZone.getDefault().getOffset(utcDate.getTime()));
}
Old answer
If your notif.At is Dateobject, it's a same question actually:
TimeZone tz = TimeZone.getDefault();
Date date = new Date();
final String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
String result = sdf.format(date);
Log.d("Date ", "date: " + result + " " + tz.getDisplayName(false, TimeZone.SHORT));
print:
date: 2015-03-31 18:45:28 GMT+08:00
You can try java.time api;
Instant date = Instant.ofEpochMilli(1549362600000l);
LocalDateTime utc = LocalDateTime.ofInstant(date, ZoneOffset.UTC);
LocalDateTime pst = LocalDateTime.ofInstant(date, ZoneOffset.of("+05:00"));
LocalDateTime is = LocalDateTime.ofInstant(date, ZoneOffset.of("+05:30"));
I'm using Time.getCurrentTimezone()to get the current timezone and therefore the date.
I'm getting and formatting it like this:
private void setDate() {
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
tvdate2.setText(today.monthDay + "-" + today.month + "-" + today.year);
}
How can I format the date according to the system settings?
I didn't manage to get it done via SimpleDateFormat...
You could get time in any format by using SimpleDateFormat class. Please refer to this
Calendar cal = Calendar.getInstance();
String currentDate = cal.get(Calendar.DAY_OF_MONTH)+"/"+(cal.get(Calendar.MONTH)+1)+"/"+cal.get(Calendar.YEAR);
Date date = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.ENGLISH).parse(currentDate);
I am facing problem where I am extracting date from Date class in android and using it in my activity, But my problem here is everything works fine but date function returns 25/03/2014 instead of current date.
Now I am confused why it is returning this irrelavent date instead of current date, Also there is no error.
My code:
import java.util.date;
SimpleDateFormat dateformat=new SimpleDateFormat("dd/mm/yyyy");
dateformat.format(new Date());
Please help to know how to get current date.
From SimpleDateFormat API reference,
d day in month
m minute in hour
M month in year
y year
Change dd/mm/yyyy to dd/MM/yyyy for day/month/year format.
Please check Time & Date settings of your emulator, sometimes that causes the issues like those as well.
Use this dude
Date date = new Date(location.getTime());
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
System.out.println("Time: " + dateFormat.format(date));
This is giving me correct time
String ntime = new SimpleDateFormat("hh:mm:ss").format(new Date());
For Date u can use
String ndate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
I want to let the user choose a Date from a DatePicker and store it into database, and then convert it to dd/mm/yyyy format.
dp =(DatePicker)findViewById(R.id.DateActivity);
setDate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
requestDate.setText("Day" + dp.getDayOfMonth() + " Month " + (dp.getMonth() + 1)+ " Year " + dp.getYear());
}
});
The output is Day 9 Month 2 Year 2014.
The output months is less by one for every month I choose so I add 1 to the month. Why this is the case?
But the main problem is how do I convert it to 09022014 and store it in the database? If the db has the format dd/mm/yyyy does it means it will not accept my output?
java.util.Calendar treats the months as a zero-based list, so the DatePicker follows this convention as well (see the documentation for DatePicker.init). It's confusing, but that's just the way Java does it (for now, at least). Adding 1 like you're doing will work just fine.
As for converting the date, you can use the SimpleDateFormat class to format the date however you like. For what you said, the format pattern string would be "ddMMyyyy". See the sample code below:
// Build Calendar object from DatePicker fields.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, myDatePicker.getMonth());
cal.set(Calendar.DAY_OF_MONTH, myDatePicker.getDayOfMonth());
cal.set(Calendar.YEAR, myDatePicker.getYear());
// Convert date to desired format.
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
String dateString = sdf.format(cal.getTime());
int dateInt = Integer.parseInt(dateString); // if you want it as an int instead
You may want to consider storing the date as 20140209 ("yyyyMMdd", year-month-day) instead for sorting purposes, as that will naturally allow it to be sorted chronologically.
For your second problem (putting it into the database) you can simply create a string like this:
String todb = dp.getDayOfMonth() + "/" + (dp.getMonth() + 1)+ "/" + dp.getYear();
Which will return a string like 09/21/2014.
Now, as for your first problem (the month being off by one), I believe this stems from a CalendarView.OnDateChangeListener. It says:
month The month that was set [0-11].
I would bet that this was also implemented on DatePicker's (or you're using the CalendarView with the DatePicker), so January is 0 and December is 11. So your way of changing the month by 1 is a perfectly fine way to do it.
I just want the date to show up like so:
Saturday, May 26, 2012 at 10:42 PM
Here's my code so far:
Calendar calendar = Calendar.getInstance();
String theDate = calendar.get(Calendar.MONTH) + " " + calendar.get(Calendar.DAY_OF_MONTH) + " " + calendar.get(Calendar.YEAR);
lastclick.setText(getString(R.string.lastclick) + " " + theDate);
This shows the numbers of the month, day, and year, but there's got to be a better way of doing this? Isn't there some simple way of doing this like using PHP's date() function?
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("EEEE, MMMM d, yyyy 'at' h:mm a");
System.out.println(format.format(calendar.getTime()));
Running the above code outputs the current time (e.g., Saturday, May 26, 2012 at 11:03 PM).
See the Android documentation for SimpleDateFormat for more information.
The format specification of SimpleDateFormat is similar to that of PHP's date function:
echo date("l, M j, Y \a\\t g:i A");
You're right. Compared to the Java code, the PHP code is much more succinct.
Use the below to format the date as required. Refer this LINK
Calendar calendar = Calendar.getInstance();
lastclick.setText(getString(R.string.lastclick) + " " + String.format("%1$tA %1$tb %1$td %1$tY at %1$tI:%1$tM %1$Tp", calendar));
Where %1$tA for staurday,
%1$tb for May,
and so on...
This is actually a fairly subtle problem to get right, and I've not seen another answer here on SO that addresses both:
The Calendar's time zone (which means that it might be showing a different date than local)
The device's Locale (which affects the "right" way to format dates)
The previous answers to this question ignore locale, and other answers that involve conversion to a Date ignore the time zone. So here's a more complete, general solution:
Calendar cal = Calendar.getInstance(); // the value to be formatted
java.text.DateFormat formatter = java.text.DateFormat.getDateInstance(
java.text.DateFormat.LONG); // one of SHORT, MEDIUM, LONG, FULL, or DEFAULT
formatter.setTimeZone(cal.getTimeZone());
String formatted = formatter.format(cal.getTime());
Note that you need to use java.text.DateFormat here, not Android's own (confusingly-named) android.text.format.DateFormat.
Even simpler answer:
SimpleDateFormat.getDateTimeInstance().format(cal.getTime())
For me this works perfectly:
val cal = Calendar.getInstance()
val pattern = "EEEE, MMMM d, yyyy 'at' h:mm a"
val primaryLocale = getLocales(resources.configuration).get(0)
val dateFormat = SimpleDateFormat(dateFormatPattern, primaryLocale)
val formatedDate: String = dateFormat.format(cal.time)
I use this solution which is a mix of the other answers and also includes time
You can customize the DateFormat.SHORT parts to other constants to show more/different details
Short leads to this on my device: 17/07/2021 04:11
You can simply pass Calendar.getInstance() to get the current time
fun formatDateTime(calendar: Calendar):String{
val formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT)
formatter.timeZone = calendar.timeZone
return formatter.format(calendar.time)
}