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

'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.

Related

Get day, month and year separately using SimpleDateFormat

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());
}

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);

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));

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

The code below gives me the current time. But it does not tell anything about milliseconds.
public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
I have a date in the format YYYY-MM-DD HH:MM:SS (2009-09-22 16:47:08).
But I want to retrieve the current time in the format YYYY-MM-DD HH:MM:SS.MS (2009-09-22 16:47:08.128, where 128 are the milliseconds).
SimpleTextFormat will work fine. Here the lowest unit of time is second, but how do I get millisecond as well?
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
A Java one liner
public String getCurrentTimeStamp() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
}
in JDK8 style
public String getCurrentLocalDateTimeStamp() {
return LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
}
You only have to add the millisecond field in your date format string:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
The API doc of SimpleDateFormat describes the format string in detail.
try this:-
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = new Date();
System.out.println(dateFormat.format(date));
or
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
tl;dr
Instant.now()
.toString()
2016-05-06T23:24:25.694Z
ZonedDateTime
.now
(
ZoneId.of( "America/Montreal" )
)
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )
2016-05-06 19:24:25.694
java.time
In Java 8 and later, we have the java.time framework built into Java 8 and later. These new classes supplant the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
Be aware that java.time is capable of nanosecond resolution (9 decimal places in fraction of second), versus the millisecond resolution (3 decimal places) of both java.util.Date & Joda-Time. So when formatting to display only 3 decimal places, you could be hiding data.
If you want to eliminate any microseconds or nanoseconds from your data, truncate.
Instant instant2 = instant.truncatedTo( ChronoUnit.MILLIS ) ;
The java.time classes use ISO 8601 format by default when parsing/generating strings. A Z at the end is short for Zulu, and means UTC.
An Instant represents a moment on the timeline in UTC with resolution of up to nanoseconds. Capturing the current moment in Java 8 is limited to milliseconds, with a new implementation in Java 9 capturing up to nanoseconds depending on your computer’s hardware clock’s abilities.
Instant instant = Instant.now (); // Current date-time in UTC.
String output = instant.toString ();
2016-05-06T23:24:25.694Z
Replace the T in the middle with a space, and the Z with nothing, to get your desired output.
String output = instant.toString ().replace ( "T" , " " ).replace( "Z" , "" ; // Replace 'T', delete 'Z'. I recommend leaving the `Z` or any other such [offset-from-UTC][7] or [time zone][7] indicator to make the meaning clear, but your choice of course.
2016-05-06 23:24:25.694
As you don't care about including the offset or time zone, make a "local" date-time unrelated to any particular locality.
String output = LocalDateTime.now ( ).toString ().replace ( "T", " " );
Joda-Time
The highly successful Joda-Time library was the inspiration for the java.time framework. Advisable to migrate to java.time when convenient.
The ISO 8601 format includes milliseconds, and is the default for the Joda-Time 2.4 library.
System.out.println( "Now: " + new DateTime ( DateTimeZone.UTC ) );
When run…
Now: 2013-11-26T20:25:12.014Z
Also, you can ask for the milliseconds fraction-of-a-second as a number, if needed:
int millisOfSecond = myDateTime.getMillisOfSecond ();
The easiest way was to (prior to Java 8) use,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
But SimpleDateFormat is not thread-safe. Neither java.util.Date. This will lead to leading to potential concurrency issues for users. And there are many problems in those existing designs. To overcome these now in Java 8 we have a separate package called java.time. This Java SE 8 Date and Time document has a good overview about it.
So in Java 8 something like below will do the trick (to format the current date/time),
LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
And one thing to note is it was developed with the help of the popular third party library joda-time,
The project has been led jointly by the author of Joda-Time (Stephen Colebourne) and Oracle, under JSR 310, and will appear in the new Java SE 8 package java.time.
But now the joda-time is becoming deprecated and asked the users to migrate to new java.time.
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project
Anyway having said that,
If you have a Calendar instance you can use below to convert it to the new java.time,
Calendar calendar = Calendar.getInstance();
long longValue = calendar.getTimeInMillis();
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
String formattedString = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
System.out.println(date.toString()); // 2018-03-06T15:56:53.634
System.out.println(formattedString); // 2018-03-06 15:56:53.634
If you had a Date object,
Date date = new Date();
long longValue2 = date.getTime();
LocalDateTime dateTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue2), ZoneId.systemDefault());
String formattedString = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
System.out.println(dateTime.toString()); // 2018-03-06T15:59:30.278
System.out.println(formattedString); // 2018-03-06 15:59:30.278
If you just had the epoch milliseconds,
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(epochLongValue), ZoneId.systemDefault());
I would use something like this:
String.format("%tF %<tT.%<tL", dateTime);
Variable dateTime could be any date and/or time value, see JavaDoc for Formatter.
I have a simple example here to display date and time with Millisecond......
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class MyClass{
public static void main(String[]args){
LocalDateTime myObj = LocalDateTime.now();
DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String forDate = myObj.format(myFormat);
System.out.println("The Date and Time are: " + forDate);
}
}
To complement the above answers, here is a small working example of a program that prints the current time and date, including milliseconds.
import java.text.SimpleDateFormat;
import java.util.Date;
public class test {
public static void main(String argv[]){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
System.out.println(strDate);
}
}
Use this to get your current time in specified format :
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.print(dateFormat.format(System.currentTimeMillis())); }
java.time
The question and the accepted answer use java.util.Date and SimpleDateFormat which was the correct thing to do in 2009. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API. Since then, it is highly recommended to stop using the legacy date-time API.
Solution using java.time, the modern date-time API:
LocalDateTime.now(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS"))
Some important points about this solution:
Replace ZoneId.systemDefault() with the applicable ZoneId e.g. ZoneId.of("America/New_York").
If the current date-time is required in the system's default timezone (ZoneId), you do not need to use LocalDateTime#now(ZoneId zone); instead, you can use LocalDateTime#now().
You can use y instead of u here but I prefer u to y.
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String args[]) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
// Replace ZoneId.systemDefault() with the applicable ZoneId e.g.
// ZoneId.of("America/New_York")
LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
String formattedDateTimeStr = ldt.format(formatter);
System.out.println(formattedDateTimeStr);
}
}
Output from a sample run in my system's timezone, Europe/London:
2023-01-02 09:53:14.353
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
I don't see a reference to this:
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmssSSS");
above format is also useful.
http://www.java2s.com/Tutorials/Java/Date/Date_Format/Format_date_in_yyyyMMddHHmmssSSS_format_in_Java.htm
Ans:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
ZonedDateTime start = Instant.now().atZone(ZoneId.systemDefault());
String startTimestamp = start.format(dateFormatter);
java.text (prior to java 8)
public static ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
};
};
...
dateFormat.get().format(new Date());
java.time
public static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
...
dateTimeFormatter.format(LocalDateTime.now());
The doc in Java 8 names it fraction-of-second , while in Java 6 was named millisecond. This brought me to confusion
You can simply get it in the format you want.
String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));

Categories

Resources