This question already has answers here:
How do I convert the date from one format to another date object in another format without using any deprecated classes?
(10 answers)
Closed 1 year ago.
How to get the Android date format "7/25/2021" to July/25/2021
Here is the portion of the code
mDisplayDate is the Textview
mDisplayDate.setOnClickListener(view -> { Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
String dateLong = month + "/" + day+ "/" + year;
mDisplayDate.setText(dateLong);
The easiest way to do this is to use a switch case
String monthStr = "";
switch(month) {
case 1:
monthStr = "January";
break;
case 2:
monthStr = "February";
break;
// and else
}
String dateLong = monthStr + "/" + day+ "/" + year;
You could use the android documentation link, that I shared in the comments to learn about SimpleDateFormat.
The Pattern to be used should be MMMM/dd/yyyy
MMMM - gives month name
dd - gives the days of the month
yyyy - gives the year
Date date = Calendar.getInstance().getTime();
DateFormat formatter = new SimpleDateFormat("MMMM/dd/yyyy");
String today = formatter.format(date);
mDisplayDate.setText(today);
Note: You may use MMM for month names in 3 letters only.
Read more about patterns here.
Related
This question already has answers here:
How to extract day, month and year from Date using Java? [duplicate]
(2 answers)
Split date/time strings
(7 answers)
Converting string to date using java8
(3 answers)
I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible?
(8 answers)
Java string to date conversion
(17 answers)
Closed 2 years ago.
So far I have the first month figured out but I still need help with the day and year. I am having trouble parsing the individual pieces and converting them to integers.
int firstSlash = date.indexOf ("/");
month = Integer.parseInt (date.substring (0, firstSlash));
That is what I have so far.
Easy way
There is a function called split() that takes the delimiter and returns an array of strings:
String[] words = date.split("/");
int month = Integer.parseInt(words[0]);
int day = Integer.parseInt(words[1]);
int year = Integer.parseInt(words[2]);
Correct way
When it comes to parsing date from string, the preferred way is using Java DateFormat API:
DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date theDate = format.parse(date);
Date object is much more powerful and allows you to interact with date and time much more fluently than bare ints
More info here!
If you know where are your month, year and day like : 25/10/2020 you can just use the split function
If you are SURE that the date will be in the right format :
String[] dateSplit = date.split("/");
int day = Integer.valueOf(dateSplit[0]);
int month = Integer.valueOf(dateSplit[1]);
int year = Integer.valueOf(dateSplit[2]);
System.out.println("year" + year);
System.out.println("month" + month);
System.out.println("day" + day);
If you are NOT SURE that the date will be in the right format :
String[] dateSplit = date.split("/");
if (dateSplit.length != 3) {
throw new Exception("Date not in valid format");
//or do something else like printing or whatever...
}
try {
int day = Integer.valueOf(dateSplit[0]);
int month = Integer.valueOf(dateSplit[1]);
int year = Integer.valueOf(dateSplit[2]);
System.out.println("year" + year);
System.out.println("month" + month);
System.out.println("day" + day);
} catch (NumberFormatException e) {
throw new Exception("Date not in valid format");
//or do something else like printing or whatever...
}
I have to put a date one week before and then 1 month before. If i try with the days one week before is working but if the day es 5 and it has to change the month is not working, it changes me the year instead. About the month it changes me the year
tring addUrl = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy");
// surround below line with try catch block as below code throws checked
// exception
Date endDate = sdf.parse(request.getParameter(field.getId()));
Calendar cal = DateToCalendar(endDate);
cal.setTime(endDate);
SimpleDateFormat formatToSend = new SimpleDateFormat("yyy-mm-dd");
case "day":
cal.add(Calendar.DATE, -1);
addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
break;
case "week":
cal.add(Calendar.DATE, -6); // number of days to add
addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
break;
default:
cal.add(Calendar.MONTH, -1); // number of days to add
addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
}
How i can do that?
Thanks
In your SimpleDateFormat objects, you should use MM for months and not mm, because mm means minutes, not months.
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
SimpleDateFormat formatToSend = new SimpleDateFormat("yyyy-MM-dd");
See the API documentation of java.text.SimpleDateFormat.
Im not sure do i fully understand the question however one potential problem is in your date format
m = Minute in hour
M = Month in year <- maybe the one you want?
See here for more examples.
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
This question already has answers here:
Julian day of the year in Java
(9 answers)
Closed 5 years ago.
I want to get the number of day.. i.e.
Jan 1 is day 1
jan 2 is day 2
Feb 1 is day 32 and december 31 is day 365 or 366 depending on leap year or not
i have used all kind of techniques such as date1 - date2 etc...
but nothing seems to work for me cant get the logic right may be.. what i want is count and add the number of the months that has gone past plus the number days of the running month i.e today is 21st Sept 2012 is day number (31(jan)+29(feb)+31(mar)+30(apr)+31(may)+30(june)+31(july)+31(aug)+20(sept)) = 264th day and they will keep adding plus one every time a day go past... thanks
mycode
int year = Calendar.getInstance().get(Calendar.YEAR);
GregorianCalendar gc = new GregorianCalendar();
gc.set(GregorianCalendar.DAY_OF_MONTH, 8);
gc.set(GregorianCalendar.MONTH, GregorianCalendar.JUNE);
gc.set(GregorianCalendar.YEAR, year);
int numberofDaysPassed=gc.get(GregorianCalendar.DAY_OF_YEAR);
numberofDaysPassed is giving me 160, undesired result
Calendar calendar = Calendar.getInstance();
int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
Or using Joda-API
DateTime dt = new DateTime();
int dayOfYear = dt.getDayOfYear();
If you need 'th' part, use switch statement
switch (dayOfYear > 20 ? (dayOfYear % 10) : dayOfYear) {
case 1: return dayOfYear + "st";
break;
case 2: return dayOfYear + "nd";
break;
case 3: return dayOfYear + "rd";
break;
default: return dayOfYear + "th";
break;
}
LocalDate
Use the LocalDate class in java.time package built into Java 8 and later.
Get the day-of-year:
int dayOfYear = LocalDate.now().getDayOfYear();
…and set the day-of-year:
LocalDate localDate = LocalDate.now().withDayOfYear( 195 );
Try setting the date on the calendar to the date in the problem, you asked for 21st Sept but you put 8th of June in the code.
Here is the updated code that gives 265 instead:
int year = Calendar.getInstance().get(Calendar.YEAR);
GregorianCalendar gc = new GregorianCalendar();
gc.set(Calendar.DAY_OF_MONTH, 21); // you asked for 21st Sept but put 8
gc.set(Calendar.MONTH, Calendar.SEPTEMBER); // you aksed for 21st Sept but put JUNE
gc.set(Calendar.YEAR, year);
int numberofDaysPassed = gc.get(Calendar.DAY_OF_YEAR);
System.out.println(numberofDaysPassed);
By the way you don't need to set the month, day etc. on Calendar, it defaults to 'now'...
Using Java 8 you can do this:
int n = LocalDate.now().get(ChronoField.DAY_OF_YEAR);
Calendar ca1 = Calendar.getInstance();
int DAY_OF_YEAR=ca1.get(Calendar.DAY_OF_YEAR);
System.out.println("Day of Year :"+DAY_OF_YEAR);
Check the result in your logcat..
DateTime dt = new DateTime();
String dayOfYear = dt.getDayOfYear().toString();
String day = "";
if(dayOfYear.endsWith("1") && !dayOfYear.endsWith("11"))
day = dayOfYear+"st";
else if(dayOfYear.endsWith("2") && !dayOfYear.endsWith("12"))
day = dayOfYear+"nd";
else if(dayOfYear.endsWith("3") && !dayOfYear.endsWith("13"))
day = dayOfYear+"rd";
else
day = dayOfYear+"th";
System.out.println("Day of year :- "+ day);
I know about to get the date in android with the help of the calender instance.
Calendar c = Calendar.getInstance();
System.out.println("====================Date is:"+ c.get(Calendar.DATE));
But with that i got only the number of the Date. . .
In My Application i have to do Some Calculation based on the Date Formate. Thus if the months get changed then that calculation will be getting wrong.
So for that reason i want the full date that gives the Month, Year and the date of the current date.
And what should be done if i want to do Some Calculation based on that date ?
As like: if the date is less then two weeks then the message should be printed. . .
Please Guide me in this.
Thanks.
Look at here,
Date cal=Calendar.getInstance().getTime();
String date = SimpleDateFormat.getDateInstance().format(cal);
for full date format look SimpleDateFormat
and IF you want to do calculation on date instance I think you should use, Calendar.getTimeInMillis() field on these milliseconds make calculation.
EDIT: these are the formats by SImpleDateFormat class.
String[] formats = new String[] {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mmZ",
"yyyy-MM-dd HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
};
for (String format : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
}
EDIT: two date difference (Edited on Date:09/21/2011)
String startTime = "2011-09-19 15:00:23"; // this is your date to compare with current date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = dateFormat.parse(startTime);
// here I make the changes.... now Date d use a calendar's date
Date d = Calendar.getInstance().getTime(); // here you can use calendar beco'z date is now deprecated ..
String systemTime =(String) DateFormat.format("yyyy-MM-dd HH:mm:ss", d.getTime());
SimpleDateFormat df1;
long diff = (d.getTime() - date1.getTime()) / (1000);
int Totalmin =(int) diff / 60;
int hours= Totalmin/60;
int day= hours/24;
int min = Totalmin % 60;
int second =(int) diff % 60;
if(day < 14)
{
// your stuff here ...
Log.e("The day is within two weeks");
}
else
{
Log.e("The day is more then two weeks");
}
Thanks.
Use SimpleDateFormat class,
String date = SimpleDateFormat.getDateInstance().format(new Date());
you can use
//try different flags for the last parameter
DateUtils.formatDateTime(context,System.currentTimeMillis(),DateUtils.FORMAT_SHOW_DATE);
for all options check http://developer.android.com/reference/android/text/format/DateUtils.html
try this,
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
int day = c.get(Calendar.DAY_OF_MONTH);
System.out.println("Current date : "
+ day + "/" + (month + 1) + "/" + year);
}
I'm using following methods to get date and time. You can change the locale here to arabic or wot ever u wish to get date in specific language.
public static String getDate(){
String strDate;
Locale locale = Locale.US;
Date date = new Date();
strDate = DateFormat.getDateInstance(DateFormat.DEFAULT, locale).format(date);
return strDate;
}
public static String getTime(){
String strTime;
Locale locale = Locale.US;
Date date = new Date();
strTime = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale).format(date);
return strTime;
}
you can get the value and save it on String as below
String Date= getDate();
String Time = getTime();
What would be the easiest way to get the current day of the week in Android?
The Java Calendar class works.
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
switch (day) {
case Calendar.SUNDAY:
// Current day is Sunday
break;
case Calendar.MONDAY:
// Current day is Monday
break;
case Calendar.TUESDAY:
// etc.
break;
}
For much better datetime handling consider using the Java 8 time API:
String day = LocalDate.now().getDayOfWeek().name()
To use this below Android SDK 26 you'll need to enable Java 8 desugaring in build.gradle:
android {
defaultConfig {
// Required when setting minSdkVersion to 20 or lower
multiDexEnabled true
}
compileOptions {
// Flag to enable support for the new language APIs
coreLibraryDesugaringEnabled true
// Sets Java compatibility to Java 8
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'
}
More information on Android's Java 8 support: https://developer.android.com/studio/write/java8-support
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
// 3 letter name form of the day
System.out.println(new SimpleDateFormat("EE", Locale.ENGLISH).format(date.getTime()));
// full name form of the day
System.out.println(new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date.getTime()));
Result (for today):
Sat
Saturday
UPDATE: java8
LocalDate date = LocalDate.now();
DayOfWeek dow = date.getDayOfWeek();
System.out.println("Enum = " + dow);
String dayName = dow.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
System.out.println("FULL = " + dayName);
dayName = dow.getDisplayName(TextStyle.FULL_STANDALONE, Locale.ENGLISH);
System.out.println("FULL_STANDALONE = " + dayName);
dayName = dow.getDisplayName(TextStyle.NARROW, Locale.ENGLISH);
System.out.println("NARROW = " + dayName);
dayName = dow.getDisplayName(TextStyle.NARROW_STANDALONE, Locale.ENGLISH);
System.out.println("NARROW_STANDALONE = " + dayName);
dayName = dow.getDisplayName(TextStyle.SHORT, Locale.ENGLISH);
System.out.println("SHORT = " + dayName);
dayName = dow.getDisplayName(TextStyle.SHORT_STANDALONE, Locale.ENGLISH);
System.out.println("SHORT_STANDALONE = " + dayName);
Result (for today):
Enum = SATURDAY
FULL = Saturday
FULL_STANDALONE = Saturday
NARROW = S
NARROW_STANDALONE = 6
SHORT = Sat
SHORT_STANDALONE = Sat
Java 8 datetime API made it so much easier :
LocalDate.now().getDayOfWeek().name()
Will return you the name of the day as String
Output : THURSDAY
Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
or
new GregorianCalendar().get(Calendar.DAY_OF_WEEK);
Just the same as in Java, nothing particular to Android.
public String weekdays[] = new DateFormatSymbols(Locale.ITALIAN).getWeekdays();
Calendar c = Calendar.getInstance();
Date date = new Date();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println(dayOfWeek);
System.out.println(weekdays[dayOfWeek]);
If you do not want to use Calendar class at all you can use this
String weekday_name = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(System.currentTimeMillis());
i.e., result is,
"Sunday"
Here is my simple approach to get Current day
public String getCurrentDay(){
String daysArray[] = {"Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday", "Saturday"};
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
return daysArray[day];
}
you can use that code for Kotlin which you will use calendar class from java into Kotlin
val day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
fun dayOfWeek() {
println("What day is it today?")
val day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
println( when (day) {
1 -> "Sunday"
2 -> "Monday"
3 -> "Tuesday"
4 -> "Wednesday"
5 -> "Thursday"
6 -> "Friday"
7 -> "Saturday"
else -> "Time has stopped"
})
}
Using both method you find easy if you wont last seven days
you use (currentdaynumber+7-1)%7,(currentdaynumber+7-2)%7.....upto 6
public static String getDayName(int day){
switch(day){
case 0:
return "Sunday";
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
}
return "Worng Day";
}
public static String getCurrentDay(){
SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE", Locale.US);
Calendar calendar = Calendar.getInstance();
return dayFormat.format(calendar.getTime());
}
Just in case you ever want to do this not on Android it's helpful to think about which day where as not all devices mark their calendar in local time.
From Java 8 onwards:
LocalDate.now(ZoneId.of("America/Detroit")).getDayOfWeek()
If you want to define the date string in strings.xml. You can do like below.
Calendar.DAY_OF_WEEK return value from 1 -> 7 <=> Calendar.SUNDAY -> Calendar.SATURDAY
strings.xml
<string-array name="title_day_of_week">
<item>日</item> <!-- sunday -->
<item>月</item> <!-- monday -->
<item>火</item>
<item>水</item>
<item>木</item>
<item>金</item>
<item>土</item> <!-- saturday -->
</string-array>
DateExtension.kt
fun String.getDayOfWeek(context: Context, format: String): String {
val date = SimpleDateFormat(format, Locale.getDefault()).parse(this)
return date?.getDayOfWeek(context) ?: "unknown"
}
fun Date.getDayOfWeek(context: Context): String {
val c = Calendar.getInstance().apply { time = this#getDayOfWeek }
return context.resources.getStringArray(R.array.title_day_of_week)[c[Calendar.DAY_OF_WEEK] - 1]
}
Using
// get current day
val currentDay = Date().getDayOfWeek(context)
// get specific day
val dayString = "2021-1-4"
val day = dayString.getDayOfWeek(context, "yyyy-MM-dd")
As DAY_OF_WEEK in GregorianCalender class is a static field you can access it directly
as foolows
int dayOfWeek = GregorianCalender.DAY_OF_WEEK;