I am formatting dates like this:
public static String toFormattedDate(#NonNull Time time, String toFormat) {
mDateFormat = new SimpleDateFormat(toFormat);
Date date = new Date();
date.setTime(time.toMillis(true));
return mDateFormat.format(date);
}
and the format I am using is:
public static final String TIME = "hh:mm a";
But it differs between the two devices that I am using for testing...
Nexus 10:
Nexus 5X:
How can I format it uniformly between devices?
You may either have to use either the 24 hour value to determine what to append so that you can add the format you desire.
public static final String TIME = "hh:mm";
and then
String ampm = Integer.parseInt(time.valueOf("hh")) >= 12 ? "PM" : "AM";
...
return mDateFormat.format(date)+" "+ampm;
Or if you feel lazy you can just do without changing the value of TIME:
return mDateFormat.format(date).toUpperCase().replace(".","");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String currentDateandTime = sdf.format(new Date());
Related
This question already has answers here:
How to determine day of week by passing specific date?
(28 answers)
Closed 7 years ago.
I have this string
String s = "29/04/2015"
And I want it to produce the name of that day in my language, which is Norwegian.
For example:
29/04/2015 is "Onsdag"
30/04/2015 is "Torsdag"
How can I do this?
String dateString = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(dateString);
SimpleDateFormat formatter = new SimpleDateFormat("E", Locale.no_NO);
String day = formatter.format(date);
Now day will have the day in given locale. Update
You need to configure an instance of DateFormat, with your locale, (take a look at https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html).
then parse the Date and get the day, as Dilip already suggests.
You can use date parsing combined with Locale settings to get the desired output. For e.g. refer following code.
String dateStr = "29/04/2015";
SimpleDateFormat dtf = new SimpleDateFormat("dd/MM/yyyy");
Date dt = dtf.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
String m = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG_FORMAT, new Locale("no", "NO"));
System.out.println(m);
For more information about locale, visit Oracle Java Documentation.
First you will need to parse the String to a Date. Then use a Calendar to get the day of the week. You can use an array to convert it to the appropriate string.
// Array of Days
final String[] DAYS = {
"søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"
};
// Parse the date
final String source = "27/04/2015";
final DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
try {
date = format.parse(source);
} catch (final ParseException e) {
e.printStackTrace();
}
// Convert to calendar
final Calendar c = Calendar.getInstance();
c.setTime(date);
final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
// Get the day's name
System.out.println("Day of Week: " + dayOfWeek);
System.out.println("Day = " + DAYS[dayOfWeek - 1]);
You need to parse your text with date to Date instance and then format it back to text. You can do it with SimpleDateFormat class which supports many patterns of dates like
dd/MM/yyyy for your original date,
and EEEE for full name of day in month.
While formatting you will also need to specify locale you want to use. To create Norway specific locale you can use for instance
Locale nor = Locale.forLanguageTag("no-NO");
So your code can look more or less like:
String text = "29/04/2015";
Locale nor = Locale.forLanguageTag("no-NO");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", nor);
SimpleDateFormat dayOfWeek = new SimpleDateFormat("EEEE", nor);
Date date = sdf.parse(text);
System.out.println(dayOfWeek.format(date));
Output: onsdag.
final int SUNDAY = 1;
final int ONSDAG = 2;
final int TORSDAG = 3;
....
....
String s = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(s);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_WEEK);
String dayString;
switch (day) {
case(ONSDAG):
dayString = "ONSDAG";
break;
....
}
EDIT: I just tested this and it actually starts from Sunday, and returns the value of 1 for sunday, I've changed the constant values to reflect this.
First you'll need a Calendar object.
Calendar cal = Calendar.getInstance();
String s = "29/04/2015"
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
cal.setTime(format.parse(s));
From the Calendar you can get the day of the week.
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
dayOfWeek will be 1-7 with Sunday (in english) being 1
You can use an HashMap map where the first parametri is the date "29/4/2015" while the second is the meaning. You can use your string to get the meaning map.get (yourString).
I am parsing the date as:
public class Consts{
public static final SimpleDateFormat DATE_FORMATTER_WITHOUT_TIME_ZONE = new SimpleDateFormat(
"yyyy-MM-dd HH:mm");
public static final SimpleDateFormat DATE_FORMATTER_2 = new SimpleDateFormat(
"MM-dd-yyyy HH:mm:ss ZZZZ");
}
cDate = new GregorianCalendar();
sDate = new GregorianCalendar();
eDate = new GregorianCalendar();
if (mStartTimeTV.getText().toString().equals("Now")) {
sDate.setTime(cDate.getTime());
} else {
sDate.setTime(Consts.DATE_FORMATTER_WITHOUT_TIME_ZONE
.parse(mStartTimeTV.getText().toString()));
}
if (!mEndTimeTV.getText().toString().equals("")) {
eDate.setTime(Consts.DATE_FORMATTER_WITHOUT_TIME_ZONE
.parse(mEndTimeTV.getText().toString()));
} else {
eDate.setTime(sDate.getTime());
// eDate = sDate;
}
And then i format the date as below before sending it to the server.:
request.addProperty("StartTime",
Consts.DATE_FORMATTER_2.format(sDate.getTime()));
request.addProperty("EndTime",
Consts.DATE_FORMATTER_2.format(eDate.getTime()));
But the thing is that on devices running 4.1.2 it is sending the date as:
Start Date: 03-23-2015 21:17:20 +0500
End Date : 10-23-2015 21:15:00 +0500
which throws exception on the server side.
But on the other devices it is sending dates as:
Start Date: 03-23-2015 21:12:13 GMT+05:00
End Date : 03-23-2015 21:16:00 GMT+05:00
which is required.
Am i doing something wrong? How can i prevent this problem so that all devices sends the same dates. (for example 03-23-2015 21:16:00 GMT+05:00)
The difference is caused by different locales set up on devices.
To mitigate the locale differences, you should use particular locale while formatting the date string. Here is a sample from my code, solving the same issue:
new SimpleDateFormat(C.FORMAT_DATETIMEZ, Locale.US).format(new Date(time))
You can extend SimpleDateFormat and override its format(...) function as following:
public class ExSimpleDateFormat extends SimpleDateFormat{
private static final long serialVersionUID = -8275126788734707527L;
public ExSimpleDateFormat() {
super();
}
public ExSimpleDateFormat(String string, Locale us) {
super(string, us);
}
#Override
public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos)
{
final StringBuffer buf = super.format(date, toAppendTo, pos);
buf.insert(buf.length() - 2, ':');
return buf;
};
}
And execute following code:
Calendar ca = Calendar.getInstance();
ca.setTimeInMillis(System.currentTimeMillis());
ExSimpleDateFormat exSimpleDateFormat = new ExSimpleDateFormat("dd-MM-yyyy HH:mm:ss 'GMT'Z", Locale.US);
exSimpleDateFormat.setTimeZone(ca.getTimeZone()); //your device timezone which can be GMT+xx:yy or GMT-xx:yy
String desiredTime = exSimpleDateFormat.format(ca.getTime());
Output would be like: 23-03-2015 23:12:52 GMT+05:00
Let me know if it helps.
Thanks
I am trying to parse the date to look like 03-23-2015 21:16:00 GMT+05:00 using joda-time but i am not able to achieve it, however it is working fine with SimpleDateFormat but for some reason i want to use Joda-Time (see my question on SO.)
Please note that i don't want to hardcode timezone to GMT+05:00 but i want to set the user's default timezone.
I am trying it as:
public class Consts{
public static final DateTimeFormatter DATE_FORMATTER_2 = DateTimeFormat
.forPattern("MM-dd-yyyy HH:mm:ss z");
public static final DateTimeFormatter DATE_FORMATTER_TEMP_1 = DateTimeFormat
.forPattern("MM-dd-yyyy HH:mm:ss Z");
}
And then i am using these formatters as:
cDate = new LocalDateTime(DateTimeZone.getDefault());
sDate = new LocalDateTime(DateTimeZone.getDefault());
eDate = new LocalDateTime(DateTimeZone.getDefault());
if (mStartTimeTV.getText().toString().equals("Now")) {
sDate = cDate;
} else {
sDate = Consts.DATE_FORMATTER_WITHOUT_TIME_ZONE
.parseLocalDateTime(mStartTimeTV.getText().toString());
}
if (!mEndTimeTV.getText().toString().equals("")) {
eDate = Consts.DATE_FORMATTER_WITHOUT_TIME_ZONE
.parseLocalDateTime(mEndTimeTV.getText().toString());
} else {
eDate = sDate;
}
And while sending the dates to the server i am formatting them as:
String s0 = Consts.DATE_FORMATTER_2.print(sDate);
String s = Consts.DATE_FORMATTER_2.withZone(
DateTimeZone.getDefault()).print(sDate);
String s1 = Consts.DATE_FORMATTER_TEMP_1.print(sDate);
But the output is always: 03-24-2015 16:07:23
I have also tried with ZZZZ but no luck.
LocalDateTime doesn't have a time zone, so there is nothing to format. You should use DateTime instead, which you can obtain using LocalDateTime.toDateTime(timeZone).
I Have a bean , in that I have one property of date type.
private Date insurance_date;
public Date getInsurance_date() {
return insurance_date;
}
public void setInsurance_date(Date insurance_date) {
this.insurance_date = insurance_date;
}
But get method gives us a date with time so I wrote a formated method as,
public String getFormatedDoI() {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String stirngDate = null ;
if(insurance_date != null)
stirngDate = df.format((insurance_date));
return stirngDate;
}
But the problem is I have date in db as 2014-05-21 , when I use getFormatedDoI() method it prints 21-00-2014. In fact for all the dates in place of month it displays 0. How can I get exact formated date.? and the database I am using is mysql. The date coming from MYSQL database.
Small mm is for minutes, capital MM is for month number, if you want to get month name you can use MMM, in your case use "dd-MM-yyy" instead of 'dd-mm-yyyy'.
public String getFormatedDoI() {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String stirngDate = null ;
if(insurance_date != null)
stirngDate = df.format((insurance_date));
return stirngDate;
}
Should solve your problem :)
mm takes minute.
If you want month then use MM.
so instead of DateFormat df = new SimpleDateFormat("dd-mm-yyyy");
use : DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
See this documentation on date format.
try
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
instead of
DateFormat df = new SimpleDateFormat("dd-mm-yyyy");
It should resolve
Use "dd-MM-yyyy" instead of "dd-mm-yyyy". The pattern "mm" stands for minutes not for month.
I have few timestamp format
time stamp format contains YYYY MM DD hh mm ss S AM/PM CountryName/CityName(zone)
YYYY-MM-DD HH:mm:ss.S
YYYY-MM-DD HH:mm:ss.S AM/PM
YYYY-MM-DD HH:mm:ss.S AM/PM z
YYYY-MM-DD HH:mm:ss.z
I want to do validation on timestamp value, If time stamp value is future value (or greater than existing) then want to show.notification message to user.
For Date format I have written following code which works to check Future date
DateTimeFormat df = DateTimeFormat.getFormat(dateFormat);
Date updateDate = df.parseStrict(newDateValue);
Date synchronizedDate = df.parseStrict(synchronizedDB_DateValue);
boolean isFutureDate = updateDate.after(synchronizedDate);
if (isFutureDate ) {
// send notification
}
else {
// do nothing
}
EDIT:
Following code only works for timestamp format = YYYY-MM-DD HH:mm:ss.S
String timestampFormat = "YYYY-MM-DD HH:mm:ss.S"; // It works
//String timestampFormat = "YYYY-MM-DD HH:mm:ss.S AM/PM";
//String timestampFormat = "YYYY-MM-DD HH:mm:ss.S AM/PM z"
//String timestampFormat = "YYYY-MM-DD HH:mm:ss.S z ";
String newTimestampFormat= timestampFormat.replaceAll("-", ".");
newTimestampFormat = newTimestampFormat.replace("YYYY", "yyyy");
newTimestampFormat = newTimestampFormat.replace("AM/PM", "a");
DateTimeFormat df = DateTimeFormat.getFormat(newTimestampFormat);
Date updateDate = df.parse(newTimeStampValue); // UPDATED VALUE = 2013.08.21 00:00:00.123
Date synchronizedDate = df.parseStrict(synchronizedDB_DateValue); // current or old db value = 2013.07.11 00:00:00.123
boolean isFutureTimestamp = updateDate.after(synchronizedDate);
if (isFutureTimestamp ) {
// send notification
}
else {
// do nothing
}
What changes I need to do for all other time-stamp format ?
Thanks in advance.
This is my solution and It Works :)
private boolean function isFutureTimestamp(){
String gwtTimestampFormat = convertToGwtTimeStampFormat(timestampFormat);
// timestampFormat = YYYY-MM-DD HH:mm:ss.S AM/PM z
// gwtTimestampFormat = yyyy.MM.dd HH:mm:ss.S a z
DateTimeFormat df = DateTimeFormat.getFormat(gwtTimestampFormat);
String newlyUpdatedTimestampValue = convertToGwtTimeStampFormat(timestampValue);
Date updatedDateTime = df.parse(newlyUpdatedTimestampValue);
String currentTimestamp = convertToGwtTimeStampFormat(currentTimestampValue);
Date currentDateTime = df.parse(currentTimestamp);
boolean isFutureTimestamp = updatedDateTime.after(currentDateTime);
return isFutureTimestamp;
}
private String convertToGwtTimeStampFormat(String gwtTimestampFormat) {
if (gwtTimestampFormat != null && gwtTimestampFormat.length() > 20) { // "2012-12-23 23:12:32.2".length= 21
gwtTimestampFormat = gwtTimestampFormat.replace("-", ".");
gwtTimestampFormat = gwtTimestampFormat.replace("YYYY", "yyyy");
gwtTimestampFormat = gwtTimestampFormat.replace("DD", "dd");
gwtTimestampFormat = gwtTimestampFormat.replace("AM/PM", "a");
return gwtTimestampFormat;
}
else {
return "";
}
}
Try using Apache DateUtils. (doc is here)
Use parseDate method(s) as it supports a wide variety of formats and can be possibly used in many other places too.
For example while using parseDate you can feed all these time stamp patterns as a string array to the following method:
public static Date parseDate(String str, String[] parsePatterns) throws ParseException
to receive Date objects.
And with this you can compare dates just like you compare numbers:
public static int truncatedCompareTo(Date date1, Date date2, int field)
This returns you a negative integer, zero, or a positive integer as the first date is less than, equal to, or greater than the second.
Notice that these methods are static so you can invoke these without needing to create a DateUtils objects. Just use DateUtils.yourMethod(yourArgs) once you have imported the jar.