How to format today's day with SimpleDateFormat? [duplicate] - java

This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 5 years ago.
Hi I am trying to get today's date but not getting proper output
import java.text.DateFormat;
import java.text.SimpleDateFormat;
private static final DateFormat sdf = new SimpleDateFormat("DD/MM/YYYY");
System.out.println("TODAY :" + sdf.format(new Date()));
output
TODAY :142/05/2017
Year and month coming properly but why the day is coming like this

D is Day in year
d is Day in month
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
EDIT: Also as #JeremyP noticed you can use yyyyfor getting year 'cause
Y is Week year

Oracle:
SimpleDateFormat is a concrete class for formatting and parsing dates
in a locale-sensitive manner. It allows for formatting (date -> text),
parsing (text -> date), and normalization.
simple y Year -Year (1996; 96)
capital Y Week year -Year (2009; 09)
simple d Day in month -Number (10)
capital D Day in year -Number (189)
capital M Month in year -Month (July; Jul; 07)
In your code:
SimpleDateFormat("DD/MM/YYYY")
Should be:
SimpleDateFormat("dd/MM/yyyy")
refer documentation for more info

According to the javadocs
D is for the day in the year and Y is for the week year.
You need to use d (lower case) for Day in month and y (lower case) for Year
This you pattern should look like:
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

Replace DD with dd and YYYY to yyyy. MM is in capital and others are in lowercase.
d = day of the month
D = day of the year
M = month in year
m = minute in hour
y = Year
Y = Week year
private static final DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("TODAY :" + sdf.format(new Date()));

Related

Getting the date as per the format in which month name is coming as first

I am getting the string in this formatas shown below
03-12-2018
I want to convert this into as below format as per Java 8 standards please advise
December 03 , 2018
what I have tried is shown below but i was not succeessful , please advise how to acheieve the same
SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String actualDate = "03-12-2018";
Date date = sdf.parse(actualDate);
String month_name = month_date.format(date);
System.out.println("Month :" + month_name);
java.time
DateTimeFormatter originalFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
DateTimeFormatter monthFirst = DateTimeFormatter
.ofLocalizedDate(FormatStyle.LONG)
.withLocale(Locale.ENGLISH);
String actualDate = "03-12-2018";
LocalDate date = LocalDate.parse(actualDate, originalFormatter);
String monthName = date.format(monthFirst);
System.out.println("Month :" + monthName);
Output:
Month :December 3, 2018
Since you are using Java 8 (and even if you didn’t), avoid the long outdated and notoriously troublesome SimpleDateFormat class. Use the built in formats where you can rather than rolling your own.
What went wrong in your code?
You parsed a string of 03-12-2018 with a format of yyyy-MM-dd. So this parses into the 2018th day of the 12th month of year 3 CE (2015 years ago). There obviously weren’t 2018 days in December. So it would have been fair to expect an exception. This is just one of the points where SimpleDateFormat is troublesome: with standard settings it just keeps counting days into the following months and years and ends up at June 9 year 9, that is, 5 and a half years later. Next you formatted this date with a formatter including month name and year, it seems you had forgot the day of month. Anyway it printed as Jun 0009 (which you should have told us in your question so that we could see what was wrong; this information can be very helpful in trying to solve your problem).
Link
Oracle tutorial: Date Time explaining how to use java.time.
It's just a matter of choosing the correct format (and applying a correct Locale):
DateTimeFormatter f = DateTimeFormatter.ofPattern("LLLL dd, yyyy");
System.out.println(f.format(yourDate));
Btw it's in the documentation:
...
Number/Text: If the count of pattern letters is 3 or greater, use the Text rules above. Otherwise use the Number rules above.
...
Use the following code:
SimpleDateFormat month_date = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String actualDate = "03-12-2018";
Date date = sdf.parse(actualDate);
String month_name = month_date.format(date);
System.out.println("Month :" + month_name);

How can I parse a date inside a string and set to a new format

I'm trying to parse 261107 as date formatted in ddmmyy
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class parse {
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
String strRawData = "A2611070830151439.5935N 102057.0442E6.68152ID=AMY123";
String strCode = strRawData.substring(0, 1);
String datetemp = strRawData.substring(1, 7);
SimpleDateFormat formatter = new SimpleDateFormat("ddmmyy");
Date datelog = formatter.parse(datetemp);
System.out.println(strCode);
System.out.println(datetemp);
System.out.println(datelog);
}
}
this code returns:
A
261107
Fri Jan 26 00:11:00 SGT 2007
dd means day in the month
MM means month (you are using mm which means minute)
yy means year
A small modification to your SimpleDateFormatter yields:
SimpleDateFormat dt = new SimpleDateFormat("ddMMyy");
Here is a cheatsheet from Change date format in a Java string
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
If you would like to format the output of the date you can use another SimpleDateFormatter and the .format(Date) method.
Here is in example of how you can do this:
public static void main(String[] args) throws ParseException {
String strRawData = "261107";
SimpleDateFormat dateParser = new SimpleDateFormat("ddMMyy"); //formatter for parsing date
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy"); //formatter for formatting date output
Date date = dateParser.parse(strRawData);
System.out.println(dateFormatter.format(date));
}
26-11-2007
You have a problem in your SimpleDateFormat.
You must use the capital M for months:
SimpleDateFormat formatter = new SimpleDateFormat("ddMMyy");
See the SimpleDateFormat table provided by Java:
Use this SimpleDateFormat:
SimpleDateFormat formatter = new SimpleDateFormat("ddMMyy");
You need to use MM not mm for months. Uppercase is months; lowercase is minutes.

Java: Date changes after parsing and applying new pattern

I'm trying to convert a user-legible time String to an SQL-compatible String. Therefore I use the following code:
// User Date
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.YYYY - HH:mm:ss");
String dateTimeUI = sdf.format(new Date());
System.out.println("UI: " + dateTimeUI);
labelDatumZeit.setText(dateTimeUI);
System.out.println("[UI]: " + dateTimeUI);
// SQL-Date
SimpleDateFormat sdf2 = new SimpleDateFormat("dd.MM.YYYY - HH:mm:ss");
Date d = sdf2.parse(dateTimeUI);
sdf2.applyPattern("yyyy-MM-dd HH:mm:ss");
dateTimeSQL = sdf2.format(d);
System.out.println("[SQL]: " + dateTimeSQL);
After converting to the new format my Data always is 2012-12-31 (+ correct time). Why is that?
YYYY is the week year. yyyy is the year. If you expect both to be the same thing, then that's where the problem is.
From the javadoc:
A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar year values.
For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible setting), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. The week year is 1998 for the last three days of calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997 and their week year is 1997.
You want to use yyyy in both format.
Your problem is that in second format you use yyyy instead of YYYY.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.YYYY - HH:mm:ss");
String dateTimeUI = sdf.format(date);
System.out.println("UI: " + dateTimeUI);
// SQL-Date
Calendar calendar = sdf.getCalendar();
calendar.setTime(date);
System.out.println(calendar.getTime());
sdf.applyPattern("YYYY-MM-dd HH:mm:ss");
String dateTimeSQL = sdf.format(calendar.getTime());
System.out.println("[SQL]: " + dateTimeSQL);

2 months on the week

I have one problem with android calendar programming, so
If there are 2 months on one week, android write me name of old month. I want him to write something like (old month-new month).
My Code is as follows
Calendar wek = Calendar.getInstance(Locale.US);
wek.add(Calendar.WEEK_OF_YEAR,r);
SimpleDateFormat gm = new SimpleDateFormat("MMM yyy");
mes.setText(gm.format(wek.getTime()));
The reason it does this is because when looking at a date represented by a week, it only looks at the first day in the week. You'd need to manually check first and last days of the week and, if they are in a different month, then format the date manually. You also need to be careful about the week overlapping the years as well. Something like this:
Calendar wek = Calendar.getInstance(Locale.US);
wek.add(Calendar.WEEK_OF_YEAR,r);
//this will set your calendar onto the first day of the week
int w = wek.get(Calendar.WEEK_OF_YEAR);
int y = wek.get(Calendar.YEAR);
wek.clear();
wek.set(Calendar.YEAR, y);
wek.set(Calendar.WEEK_OF_YEAR, w);
//get the month and year of the first day of the week
int m1 = wek1.get(Calendar.MONTH);
int y1 = wek1.get(Calendar.YEAR);
//get the date for the end of the week and its month and year
Calendar w2 = wek;
w2.add(Calendar.DATE, 6);
int m2 = w2.get(Calendar.MONTH);
int y2 = w2.get(Calendar.YEAR);
if(m1 == m2) {
//if the two months are the same, then just format the date
SimpleDateFormat gm = new SimpleDateFormat("MMM yyyy");
mes.setText(gm.format(wek.getTime()));
}
else if(y1 == y1) {
//different months, same year - format as "MMM - MMM yyyy"
SimpleDateFormat gm = new SimpleDateFormat("MMM");
SimpleDateFormat gy = new SimpleDateFormat("yyyy");
mes.setTextText(gm.format(wek.getTime()) + " - " +
gm.format(w2.getTime()) + " " +
gy.format(wek.getTime()));
}
else {
//Different months and different years - format as "MMM yyyy - MMM yyyy"
SimpleDateFormat gm = new SimpleDateFormat("MMM yyyy");
mes.setTextText(gm.format(wek.getTime()) + " - " +
gm.format(w2.getTime()));
}
And what is the correct month you think? What you do is add r weeks to the exact moment of now. This is specific point in time and is associated with particular millisecond. This millisecond belongs either to one or the other month. And your code returns which month is that.
You should get the index of the first day of week, and the last one and check the month they belong to.
(I am not a native speaker but you could say that a week overlaps two months, more than a week on 2 months.)

Challenging Java/Groovy Date Manipulation

I have a bunch of dates formatted with the year and week, as follows:
2011-10
The week value is the week of the year(so 1-52). From this week value, I need to output something like the following:
Mar 7
Explicitly, I need the Month that the given week is in, and the date of the first Monday of that week. So in other words it is saying that the 10th week of the year is the week of March 7th.
I am using Groovy. What kind of date manipulation can I do to get this to work?
Here's a groovy solution:
use(groovy.time.TimeCategory) {
def (y, w) = "2011-10".tokenize("-")
w = ((w as int) + 1) as String
def d = Date.parse("yyyy-w", "$y-$w") + 1.day
println d.format("MMM dd")
}
Use a GregorianCalendar (or Joda, if you don't mind a dependency)
String date = "2011-10";
String[] parts = date.split("-");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, Integer.parseInt(parts[0]));
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(parts[1])+1);
DateFormat df = new SimpleDateFormat("MMM d");
System.out.println(df.format(cal.getTime()) + " (" + cal.getTime() + ")");
EDIT: Added +1 to week, since calendar uses zero-based week numbers
Date date = new SimpleDateFormat("yyyy-w", Locale.UK).parse("2011-10");
System.out.println(new SimpleDateFormat("MMM d").format(date));
The first line returns first day of the 10th week in British Locale (March 7th). When Locale is not enforced, the results are dependent on default JVM Locale.
Formats are explained here.
You can use SimpleDateFormat, just like in java. See groovyconsole.appspot.com/script/439001
java.text.DateFormat df = new java.text.SimpleDateFormat('yyyy-w', new Locale('yourlocale'))
Date date = df.parse('2011-10')
To add a week, simply use Date date = df.parse('2011-10')+7
You don't need to set the Locale if your default Locale is using Monday as the first day of week.

Categories