Get day, month and year separately using SimpleDateFormat - java

I have a SimleDateFormat like this
SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy hh:mm");
String date = format.format(Date.parse(payback.creationDate.date));
I'm giving date with the format like "Jan,23,2014".
Now, I want to get day, month and year separately. How can I implement this?

If you need to get the values separately, then use more than one SimpleDateFormat.
SimpleDateFormat dayFormat = new SimpleDateFormat("dd");
String day = dayFormat.format(Date.parse(payback.creationDate.date));
SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
String month = monthFormat .format(Date.parse(payback.creationDate.date));
etc.

SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy hh:mm", Locale.ENGLISH);
Date theDate = format.parse("JAN 13,2014 09:15");
Calendar myCal = new GregorianCalendar();
myCal.setTime(theDate);
System.out.println("Day: " + myCal.get(Calendar.DAY_OF_MONTH));
System.out.println("Month: " + myCal.get(Calendar.MONTH) + 1);
System.out.println("Year: " + myCal.get(Calendar.YEAR));

Wow, SimpleDateFormat for getting string parts? It can be solved much easier if your input string is like "Jan,23,2014":
String input = "Jan,23,2014";
String[] out = input.split(",");
System.out.println("Year = " + out[2]);
System.out.println("Month = " + out[0]);
System.out.println("Day = " + out[1]);
Output:
Year = 2014
Month = Jan
Day = 23
But if you really want to use SimpleDateFormat because of some reason, the solution will be the following:
String input = "Jan,23,2014";
SimpleDateFormat format = new SimpleDateFormat("MMM,dd,yyyy");
Date date = format.parse(input);
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
calendar.setTime(date);
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
System.out.println(new SimpleDateFormat("MMM").format(calendar.getTime()));
Output:
2014
23
Jan

The accepted answer here suggests to use more than one SimpleDateFormat, but it's possible to do this using one SimpleDateFormat instance and calling applyPattern.
Note: I believe this post would also be helpful for those who were searching for setPattern() just like me.
Date date=new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
simpleDateFormat.applyPattern("dd");
System.out.println("Day : " + simpleDateFormat.format(date));
simpleDateFormat.applyPattern("MMM");
System.out.println("Month : " + simpleDateFormat.format(date));
simpleDateFormat.applyPattern("yyyy");
System.out.println("Year : " + simpleDateFormat.format(date));

tl;dr
Use LocalDate class.
LocalDate
.parse(
"Jan,23,2014" ,
DateTimeFormatter.ofPattern( "MMM,dd,uuuu" , Locale.US )
)
.getYear()
… or .getMonthValue() or .getDayOfMonth.
java.time
The other Answers use outmoded classes. The java.time classes supplant those troublesome old legacy classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
String input = "Jan,23,2014";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM,d,uuuu" );
LocalDate ld = LocalDate.parse( input , f );
Interrogate for the parts you want.
int year = ld.getYear();
int month = ld.getMonthValue();
int dayOfMonth = ld.getDayOfMonth();
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Use this to parse "Jan,23,2014"
SimpleDateFormat fmt = new SimpleDateFormat("MMM','dd','yyyy");
Date dt = fmt.parse("Jan,23,2014");
then you can get whatever part of the date.

Are you accepting this ?
int day = 25 ; //25
int month =12; //12
int year = 1988; // 1988
Calendar c = Calendar.getInstance();
c.set(year, month-1, day, 0, 0);
SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy hh:mm");
System.out.println(format.format(c.getTime()));
Display as Dec 25,1988 12:00
UPDATE : based on Comment
DateFormat format = new SimpleDateFormat("MMM");
System.out.println(format.format(format.parse("Jan,23,2014")));
NOTE: Date.parse() is #deprecated and as per API it is recommend to use DateFormat.parse

public static String getDate(long milliSeconds, String dateFormat) {
// Create a DateFormatter object for displaying date in specified
// format.
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat,
Locale.getDefault());
// Create a calendar object that will convert the date and time value in
// milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}

Related

How to reformat time format?

I am working on android project and i receive from API the time in format like this "10:12:57 am" (12 hour format) and I want to display it in format "10:12" just like this (on a 24 hour clock). How to reformat that time?
So 12:42:41 am should become 00:42. And 02:13:39 pm should be presented as 14:13.
Using java.time (Modern Approach)
String str = "10:12:57 pm";
DateTimeFormatter formatter_from = DateTimeFormatter.ofPattern( "hh:mm:ss a", Locale.US ); //Use pattern symbol "hh" for 12 hour clock
LocalTime localTime = LocalTime.parse(str.toUpperCase(), formatter_from );
DateTimeFormatter formatter_to = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US ); // "HH" stands for 24 hour clock
System.out.println(localTime.format(formatter_to));
See BasilBourque answer below and OleV.V. answer here for better explanation.
Using SimpleDateFormat
String str = "10:12:57 pm";
SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss a", Locale.US);
//Locale is optional. You might want to add it to avoid any cultural differences.
SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm", Locale.US);
try {
Date d = formatter_from.parse(str);
System.out.println(formatter_to.format(d));
} catch (ParseException e) {
e.printStackTrace();
}
If your input is 10:12:57 am, output will be 10:12. And if string is 10:12:57 pm, output will be 22:12.
tl;dr
LocalTime // Represent a time-of-day, without a date and without a time zone.
.parse( // Parse an input string to be a `LocalTime` object.
"10:12:57 am".toUpperCase() , // The cultural norm in the United States expects the am/pm to be in all-uppercase. So we convert our input value to uppercase.
DateTimeFormatter.ofPattern( "hh:mm:ss a" , Locale.US ) // Specify a formatting pattern to match the input.
) // Returns a `LocalTime` object.
.format( // Generate text representing the value in this date-time object.
DateTimeFormatter.ofPattern( "HH:mm" , Locale.US ) // Note that `HH` in uppercase means 24-hour clock, not 12-hour.
) // Returns a `String`.
10:12
java.time
The modern approach uses the java.time classes that years ago supplanted the terrible Date & Calendar & SimpleDateFormat classes.
The LocalTime class represents a time-of-day in a generic 24-hour day, without a date and without a time zone.
Parse your string input as a LocalTime object.
String input = ( "10:12:57 am" );
DateTimeFormatter fInput = DateTimeFormatter.ofPattern( "HH:mm:ss a" , Locale.US );
LocalTime lt = LocalTime.parse( input.toUpperCase() , fInput ); // At least in the US locale, the am/pm is expected to be in all uppercase: AM/PM. So we call `toUppercase` to convert input accordingly.
lt.toString(): 10:12:57
Generate a String with text in the hour-minute format you desire. Note that HH in uppercase means 24-hour clock.
DateTimeFormatter fOutput = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US );
String output = lt.format( fOutput );
output: 10:12
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Try this:
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
try {
Date date = parseFormat.parse("10:12:57 pm");
System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
}
catch (Exception e) {
e.printStackTrace();
}
The gives:
10:12:57 pm = 22:12
You can use such formatters:
SimpleDateFormat formatterFrom = new SimpleDateFormat("hh:mm:ss aa");
SimpleDateFormat formatterTo = new SimpleDateFormat("HH:mm");
Date date = formatterFrom.parse("10:12:57 pm");
System.out.println(formatterTo.format(date));
String str ="10:12:57 pm";
SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss aa", Locale.US);
SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm",Locale.US);
try {
Date d = formatter_from.parse(str);
System.out.println(formatter_to.format(d));
} catch (ParseException e) {
e.printStackTrace();
}

Android how to get tomorrow's date

In my android application. I need to display tomorrow's date, for example today is 5th March so I need to display as 6 March. I know the code for getting today's date, month and year.
date calculating
GregorianCalendar gc = new GregorianCalendar();
yearat = gc.get(Calendar.YEAR);
yearstr = Integer.toString(yearat);
monthat = gc.get(Calendar.MONTH) + 1;
monthstr = Integer.toString(monthat);
dayat = gc.get(Calendar.DAY_OF_MONTH);
daystr = Integer.toString(dayat);
If I have the code
dayat = gc.get(Calendar.DAY_OF_MONTH) + 1;
will it display tomorrow's date. or just add one to today's date? For example, if today is January 31. With the above code, will it display like 1 or 32? If it displays 32, what change I need to make?
Get today's date as a Calendar.
Add 1 day to it.
Format for display purposes.
For example,
GregorianCalendar gc = new GregorianCalendar();
gc.add(Calendar.DATE, 1);
// now do something with the calendar
Use the following code to display tomorrow date
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
Use SimpleDateFormat to format the Date as a String:
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
String todayAsString = dateFormat.format(today);
String tomorrowAsString = dateFormat.format(tomorrow);
System.out.println(todayAsString);
System.out.println(tomorrowAsString);
Prints:
05-Mar-2014
06-Mar-2014
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
you have to add just 1 in your Calendar Day.
GregorianCalendar gc = new GregorianCalendar();
gc.add(Calendar.DATE, 1);
java.util.Date and java.util.Calendar are terrible to work with. I suggest you use JodaTime which has a much cleaner / nicer API. JodaTime is pretty standard these days.
http://www.joda.org/joda-time/#Why_Joda-Time
Note that JDK 8 will introduce a new date/time API heavily influenced by JodaTime.
http://java.dzone.com/articles/introducing-new-date-and-time
https://jcp.org/en/jsr/detail?id=310
Other options:
Calendar tomorrow = Calendar.getInstance();
tomorrow.roll(Calendar.DATE, true);
or
tomorrow.roll(Calendar.DATE, 1);
roll can also be used to go back in time by passing a negative number, so for example:
Calendar yesterday = Calendar.getInstance();
yesterday.roll(Calendar.DATE, -1);
the first answers pretty much covers the possibilities.
but here one another solution which you can use from org.apache.commons.lang.time:
Date lTomorrow = DateUtils.addDays(new Date(), 1);
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Instead use either Joda-Time library or the new java.time package in bundled with Java 8.
Some example code using the Joda-Time 2.3 library.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = new DateTime( timeZone );
DateTime tomorrow = now.plusDays( 1 );
String output = DateTimeFormat.forPattern( "FF" ).withLocale(Locale.FRANCE).print( tomorrow );
Get todays date by using calendar and then add 1 day to it.
This is working to me well!!
Date currentDate = new Date();// get the current date
currentDate.setDate(currentDate.getDate() + 1);//add one day to the current date
dateView.setText(currentDate.toString().substring(0, 10));// put the string in specific format in my textView
good luck!!
much easier now
String today = LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM-dd"));
String tomorrow = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("MM-dd"));
Try like this..
dayat = gc.add(Calendar.DATE, 1);
tl;dr
java.time.LocalDate.now()
.plusDays( 1 )
java.time
All the other Answers are outmoded, using the troublesome old Date & Calendar classes or the Joda-Time project which is now in maintenance mode. The modern approach uses the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
From that LocalDate you can do math to get the following day.
LocalDate tomorrow = today.plusDays( 1 ) ;
Strings
To generate a String representing the LocalDate object’s value, call toString for text formatted per the ISO 8601 standard: YYYY-MM-DD.
To generate strings in other formats, search Stack Overflow for DateTimeFormatter.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
Best way for setting next day is
public void NextDate()
{
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
e_date.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(mDay+1).append("-").append(mMonth + 1).append("-")
.append(mYear).append(" "));
}
Just call this method and send date from which you want next date
public String nextDate(Date dateClicked) {
//
String next_day;
calander_view.setCurrentDayTextColor(context.getResources().getColor(R.color.white_color));
//calander_view.setCurrentDayBackgroundColor(context.getResources().getColor(R.color.gray_color));
SimpleDateFormat dateFormatForDisplaying = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
String date_format = dateFormatForDisplaying.format(dateClicked);
SimpleDateFormat simpleDateformat = new SimpleDateFormat("E"); // the day of the week abbreviated
final Calendar calendar = Calendar.getInstance();
try {
Date date = dateFormatForDisplaying.parse(date_format);
calendar.setTime(date);
calendar.add(Calendar.DATE, 1);
String nex = dateFormatForDisplaying.format(calendar.getTime());
Date d1 = dateFormatForDisplaying.parse(nex);
String day_1 = simpleDateformat.format(d1);
next_day = nex + ", " + day_1;
} catch (ParseException e) {
e.printStackTrace();
}
return next_day;
}
String lastDate="5/28/2018";
Calendar calendar = Calendar.getInstance();
String[] sDate=lastDate.split("/");
calendar.set(Integer.parseInt(sDate[2]),Integer.parseInt(sDate[0]),Integer.parseInt(sDate[1]));
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
// String todayAsString = dateFormat.format(today);
for (int i=1;i<29;i++)
{
calendar.add(Calendar.DAY_OF_YEAR,1);
// td[i].setText(dateFormat.format(calendar.getTime()));
System.out.println(dateFormat.format(calendar.getTime()));
}

Android: how to get the current day of the week (Monday, etc...) in the user's language?

I want to know what the current day of the week is (Monday, Tuesday...) in the user's local language. For example, "Lundi" "Mardi" etc... if the user is French.
I have read this post, it but it only returns an int, not a string with the day in the user's language: What is the easiest way to get the current day of the week in Android?
More generally, how do you get all the days of the week and all the months of the year written in the user's language ?
I think that this is possible, as for example the Google agenda gives the days and months written in the user's local language.
Use SimpleDateFormat to format dates and times into a human-readable string, with respect to the users locale.
Small example to get the current day of the week (e.g. "Monday"):
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
Try this:
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
String weekday = new DateFormatSymbols().getShortWeekdays()[dayOfWeek];
I know already answered but who looking for 'Fri' like this
for Fri -
SimpleDateFormat sdf = new SimpleDateFormat("EEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
and who wants full date string they can use 4E for Friday
For Friday-
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
Enjoy...
To make things shorter You can use this:
android.text.format.DateFormat.format("EEEE", date);
which will return day of the week as a String.
Hers's what I used to get the day names (0-6 means monday - sunday):
public static String getFullDayName(int day) {
Calendar c = Calendar.getInstance();
// date doesn't matter - it has to be a Monday
// I new that first August 2011 is one ;-)
c.set(2011, 7, 1, 0, 0, 0);
c.add(Calendar.DAY_OF_MONTH, day);
return String.format("%tA", c);
}
public static String getShortDayName(int day) {
Calendar c = Calendar.getInstance();
c.set(2011, 7, 1, 0, 0, 0);
c.add(Calendar.DAY_OF_MONTH, day);
return String.format("%ta", c);
}
Try this...
//global declaration
private TextView timeUpdate;
Calendar calendar;
.......
timeUpdate = (TextView) findViewById(R.id.timeUpdate); //initialize in onCreate()
.......
//in onStart()
calendar = Calendar.getInstance();
//date format is: "Date-Month-Year Hour:Minutes am/pm"
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm a"); //Date and time
String currentDate = sdf.format(calendar.getTime());
//Day of Name in full form like,"Saturday", or if you need the first three characters you have to put "EEE" in the date format and your result will be "Sat".
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
Date date = new Date();
String dayName = sdf_.format(date);
timeUpdate.setText("" + dayName + " " + currentDate + "");
The result is...
tl;dr
String output =
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.getDayOfWeek()
.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
java.time
The java.time classes built into Java 8 and later and back-ported to Java 6 & 7 and to Android include the handy DayOfWeek enum.
The days are numbered according to the standard ISO 8601 definition, 1-7 for Monday-Sunday.
DayOfWeek dow = DayOfWeek.of( 1 );
This enum includes the getDisplayName method to generate a String of the localized translated name of the day.
The Locale object specifies a human language to be used in translation, and specifies cultural norms to decide issues such as capitalization and punctuation.
String output = DayOfWeek.MONDAY.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
To get today’s date, use the LocalDate class. Note that a time zone is crucial as for any given moment the date varies around the globe.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DayOfWeek dow = today.getDayOfWeek();
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
Keep in mind that the locale has nothing to do with the time zone.two separate distinct orthogonal issues. You might want a French presentation of a date-time zoned in India (Asia/Kolkata).
Joda-Time
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
The Joda-Time library provides Locale-driven localization of date-time values.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
Locale locale = Locale.CANADA_FRENCH;
DateTimeFormatter formatterUnJourQuébécois = DateTimeFormat.forPattern( "EEEE" ).withLocale( locale );
String output = formatterUnJourQuébécois.print( now );
System.out.println("output: " + output );
output: samedi
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
Sorry for late reply.But this would work properly.
daytext=(textview)findviewById(R.id.day);
Calender c=Calender.getInstance();
SimpleDateFormat sd=new SimpleDateFormat("EEEE");
String dayofweek=sd.format(c.getTime());
daytext.setText(dayofweek);
I just use this solution in Kotlin:
var date : String = DateFormat.format("EEEE dd-MMM-yyyy HH:mm a" , Date()) as String
If you are using ThreetenABP date library bt Jake Warthon you can do:
dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault()
on your dayOfWeek instance. More at:
https://github.com/JakeWharton/ThreeTenABP https://www.threeten.org/threetenbp/apidocs/org/threeten/bp/format/TextStyle.html
//selected date from calender
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); //Date and time
String currentDate = sdf.format(myCalendar.getTime());
//selcted_day name
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
String dayofweek=sdf_.format(myCalendar.getTime());
current_date.setText(currentDate);
lbl_current_date.setText(dayofweek);
Log.e("dayname", dayofweek);

convert date from "2009-12 Dec" format to "31-DEC-2009"

'2009-12 Dec' should be converted to '31-DEC-2009'
'2010-09 Sep' should be converted to '30-SEP-2010'
'2010-02 Feb' should be converted to '28-FEB-2010'
'2008-02 Feb' should be converted to '29-FEB-2008'
The values 2009-12 Dec, 2008-02 Feb will be displayed to the User in a drop down. The User have no option to select the DAY.
The user selected value should be passed to the Database. But the database expects the date in the format DD-MMM-YYYY. The query has '<= USER_DATE' condition. So, the last day of the month should be automatically selected and passed to the database.
Pl help me in writing the function that does the above job.
static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM MMM");
public static String convertMapedToSqlFormat(final String maped) {
String convertedMaped = null;
//....
return convertedMaped;
}
#Test
public void testConvertMapedToSqlFormat() {
String[] mapedValues = { "2009-12 Dec", "2009-11 Nov", "2009-10 Oct",
"2009-09 Sep", "2009-08 Aug", "2009-07 Jul", "2009-06 Jun",
"2009-05 May", "2009-04 Apr", "2009-03 Mar", "2009-02 Feb",
"2009-01 Jan", "2008-12 Dec", "2008-11 Nov", "2008-10 Oct" };
for (String maped : mapedValues) {
System.out.println(convertMapedToSqlFormat(maped));
}
}
Convert it to Calendar and use Calendar#getActualMaximum() to obtain last day of month and set the day with it.
Kickoff example:
String oldString = "2009-12 Dec";
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("yyyy-MM").parse(oldString)); // Yes, month name is ignored but we don't need this.
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
String newString = new SimpleDateFormat("dd-MMM-yyyy").format(calendar.getTime()).toUpperCase();
System.out.println(newString); // 31-DEC-2009
Use your DateFormat (but fix it to yyyy-dd MMM) to parse the date
convert the Date to Calendar
Use Calendar.getActualMaximim()
use dd-MMM-yyyy to format the obtained date.
call .toUpperCase()
So:
static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM MMM");
static SimpleDateFormat dbDateFormat = new SimpleDateFormat("yyyy-MMM-dd");
public static String convertMapedToSqlFormat(final String maped) {
Date date = dateFormat.parse(mapped);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
return dbDateFormat.format(cal.getTime()).toUpperCase();
}
A few notes:
if possible use joda-time DateTime
avoid having strict date formats in the database.
Get the year and month from the YYYY-MM part of the string.
Use JODA to create a point in time corresponding to the first day of that month. Move one month forward, and one day backward. Flatten the time to the string representation you need.
Hi you have to parse your date,
like so
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date du = new Date();
du = df.parse(sDate);
df = new SimpleDateFormat("yyyy-MM-dd");
sDate = df.format(du);
Hope this helps.
Let me know if it does.
PK
java.time
Much easier now with the modern java.time classes that supplant the troublesome old date-time classes seen here in the Question and other Answers.
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
Now in maintenance mode, the Joda-Time project also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
YearMonth
The YearMonth class provides just what you want.
YearMonth start = YearMonth.of( 2008 , Month.OCTOBER );
YearMonth stop = YearMonth.of( 2009 , Month.DECEMBER );
List<YearMonth> yms = new ArrayList<>();
YearMonth ym = start ;
while( ! ym.isAfter( stop ) ) {
yms.add( ym );
// Set up the next loop.
ym = ym.plusMonths( 1 );
}
To present, use a DateTimeFormatter to generate a String representation of the YearMonth value.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM MMM" );
f = f.withLocale( Locale.CANADA_FRENCH ); // Or Locale.US etc.
String output = ym.format( f );
To get the last day of the month, interrogate the YearMonth object.
LocalDate endOfMonth = ym.atEndOfMonth();
To present, use a DateTimeFormatter. Either let instantiate a formatter that automatically localizes appropriate to a specified Locale, or specify your own formatting pattern. Shown many times in many other Questions and Answers on Stack Overflow.

How can I change the date format in Java? [duplicate]

This question already has answers here:
java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
(8 answers)
Closed 3 years ago.
I need to change the date format using Java from
dd/MM/yyyy to yyyy/MM/dd
How to convert from one date format to another using SimpleDateFormat:
final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";
// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
sdf.format(new Date());
This should do the trick
tl;dr
LocalDate.parse(
"23/01/2017" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK )
).format(
DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK )
)
2017/01/23
Avoid legacy date-time classes
The answer by Christopher Parker is correct but outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.
Using java.time
Parse the input string as a date-time object, then generate a new String object in the desired format.
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter fIn = DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK ); // As a habit, specify the desired/expected locale, though in this case the locale is irrelevant.
LocalDate ld = LocalDate.parse( "23/01/2017" , fIn );
Define another formatter for the output.
DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK );
String output = ld.format( fOut );
2017/01/23
By the way, consider using standard ISO 8601 formats for strings representing date-time values.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section here is left for the sake of history.
For fun, here is his code adapted for using the Joda-Time library.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";
// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;
DateTimeFormatter formatterOld = DateTimeFormat.forPattern(OLD_FORMAT);
DateTimeFormatter formatterNew = DateTimeFormat.forPattern(NEW_FORMAT);
LocalDate localDate = formatterOld.parseLocalDate( oldDateString );
newDateString = formatterNew.print( localDate );
Dump to console…
System.out.println( "localDate: " + localDate );
System.out.println( "newDateString: " + newDateString );
When run…
localDate: 2010-08-12
newDateString: 2010/08/12
Use SimpleDateFormat
String DATE_FORMAT = "yyyy/MM/dd";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Formated Date " + sdf.format(date));
Complete Example:
import java.text.SimpleDateFormat;
import java.util.Date;
public class JavaSimpleDateFormatExample {
public static void main(String args[]) {
// Create Date object.
Date date = new Date();
// Specify the desired date format
String DATE_FORMAT = "yyyy/MM/dd";
// Create object of SimpleDateFormat and pass the desired date format.
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
/*
* Use format method of SimpleDateFormat class to format the date.
*/
System.out.println("Today is " + sdf.format(date));
}
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date myDate = sdf.parse("28/12/2013");
sdf.applyPattern("yyyy/MM/dd")
String myDateString = sdf.format(myDate);
Now myDateString = 2013/12/28
This is just Christopher Parker's answer adapted to use the new1 classes from Java 8:
final DateTimeFormatter OLD_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy");
final DateTimeFormatter NEW_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String oldString = "26/07/2017";
LocalDate date = LocalDate.parse(oldString, OLD_FORMATTER);
String newString = date.format(NEW_FORMATTER);
1 well, not that new anymore, Java 9 should be released soon.
Or you could go the regex route:
String date = "10/07/2010";
String newDate = date.replaceAll("(\\d+)/(\\d+)/(\\d+)", "$3/$2/$1");
System.out.println(newDate);
It works both ways too. Of course this won't actually validate your date and will also work for strings like "21432/32423/52352". You can use "(\\d{2})/(\\d{2})/(\\d{4}" to be more exact in the number of digits in each group, but it will only work from dd/MM/yyyy to yyyy/MM/dd and not the other way around anymore (and still accepts invalid numbers in there like 45). And if you give it something invalid like "blabla" it will just return the same thing back.
many ways to change date format
private final String dateTimeFormatPattern = "yyyy/MM/dd";
private final Date now = new Date();
final DateFormat format = new SimpleDateFormat(dateTimeFormatPattern);
final String nowString = format.format(now);
final Instant instant = now.toInstant();
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern(
dateTimeFormatPattern).withZone(ZoneId.systemDefault());
final String formattedInstance = formatter.format(instant);
/* Java 8 needed*/
LocalDate date = LocalDate.now();
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);
To Change the format of Date you have Require both format look below.
String stringdate1 = "28/04/2010";
try {
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = format1.parse()
SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd");
String stringdate2 = format2.format(date1);
} catch (ParseException e) {
e.printStackTrace();
}
here stringdate2 have date format of yyyy/MM/dd. and it contain 2010/04/28.
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(format1.format(date));

Categories

Resources