Displaying AM and PM in lower case after date formatting - java

After formatting a datetime, the time displays AM or PM in upper case, but I want it in lower case like am or pm.
This is my code:
public class Timeis {
public static void main(String s[]) {
long ts = 1022895271767L;
String st = null;
st = new SimpleDateFormat(" MMM d 'at' hh:mm a").format(ts);
System.out.println("time is " + ts);
}
}

This works
public class Timeis {
public static void main(String s[]) {
long ts = 1022895271767L;
SimpleDateFormat sdf = new SimpleDateFormat(" MMM d 'at' hh:mm a");
// CREATE DateFormatSymbols WITH ALL SYMBOLS FROM (DEFAULT) Locale
DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
// OVERRIDE SOME symbols WHILE RETAINING OTHERS
symbols.setAmPmStrings(new String[] { "am", "pm" });
sdf.setDateFormatSymbols(symbols);
String st = sdf.format(ts);
System.out.println("time is " + st);
}
}

Unfortunately the standard formatting methods don't let you do that. Nor does Joda. I think you're going to have to process your formatted date by a simple post-format replace.
String str = oldstr.replace("AM", "am").replace("PM","pm");
You could use the replaceAll() method that uses regepxs, but I think the above is perhaps sufficient. I'm not doing a blanket toLowerCase() since that could screw up formatting if you change the format string in the future to contain (say) month names or similar.
EDIT: James Jithin's solution looks a lot better, and the proper way to do this (as noted in the comments)

If you don't want to do string substitution, and are using Java 8 javax.time:
Map<Long, String> ampm = new HashMap<>();
ampm.put(0l, "am");
ampm.put(1l, "pm");
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendPattern("E M/d h:mm")
.appendText(ChronoField.AMPM_OF_DAY, ampm)
.toFormatter()
.withZone(ZoneId.of("America/Los_Angeles"));
It's necessary to manually build a DateTimeFormatter (specifying individual pieces), as there is no pattern symbol for lowercase am/pm. You can use appendPattern before and after.
I believe there is no way to substitute the default am/pm symbols, making this is the only way short of doing the string replace on the final string.

Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("HH:mm a");
String formattedDate = df.format(c.getTime());
formattedDate = formattedDate.replace("a.m.", "AM").replace("p.m.","PM");
TextView textView = findViewById(R.id.textView);
textView.setText(formattedDate);

Try this:
System.out.println("time is " + ts.toLowerCase());
Although you may be able to create a custom format as detailed here and here
Unfortunately out of the box the AM and PM do not seem to be customisable in the standard SimpleDateFormat class

James's answer is great if you want different style other than default am, pm. But I'm afraid you need mapping between Locale and Locale specific AM/PM set to adopting the override. Now you simply use java built-in java.util.Formatter class. So an easy example looks like this:
System.out.println(String.format(Locale.UK, "%1$tl%1$tp", LocalTime.now()));
It gives:
9pm
To note that if you want upper case, just replace "%1$tp" with "%1$Tp". You can find more details at http://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#dt.

String today = now.format(new DateTimeFormatterBuilder()
.appendPattern("MM/dd/yyyy ")
.appendText(ChronoField.AMPM_OF_DAY)
.appendLiteral(" (PST)")
.toFormatter(Locale.UK));
// output => 06/18/2019 am (PST)
Locale.UK => am or pm;
Locale.US => AM or PM; try different locale for your needs (defaul, etc.)

new SimpleDateFormat("MMM d 'at' hh:mm a", new Locale("en", "IN"));
change to a locale that uses am/pm instead of AM/PM.

just add toLowarCase() like this
public class Timeis {
public static void main(String s[]) {
long ts = 1022895271767L;
String st = null;
st = new SimpleDateFormat(" MMM d 'at' hh:mm a").format(ts).toLowerCase();
System.out.println("time is " + ts);
}
}
and toUpperCase() if you want upper case

This is how we perform in android studio's java code pass unix timestamp as parameter
private String convertTimeToTimeStamp(Long timeStamp){
SimpleDateFormat sdf=new SimpleDateFormat("hh:mm aaa", Locale.getDefault());
return sdf.format(timeStamp);
}
function returns time of format 09:30 PM

Related

Convert hour interval to 24h interval

I would like to convert "9:00 am – 11:00 pm" -> "9:00 - 23:00", how can I do that? What I've tried so far:
if(input.contains("am")) { //This because I have a string with other kind of items too (not only these interval of hours but names, etc)
DateFormat df = new SimpleDateFormat("h:mm a – h:mm a");
DateFormat outputformat = new SimpleDateFormat("HH:mm - HH:mm");
Date date = null;
String output = null;
date= df.parse(input);
input = outputformat.format(date);
System.out.println("Output: "+output);
}
but the output is wrong, in the example 23:00 - 23:00 because it doesn't recognize the first and the second hour
I tried also something like:
DateFormat df = new SimpleDateFormat("h:mm a" +" - "+ "h:mm a");
DateFormat outputformat = new SimpleDateFormat("HH:mm"+" - "+ "HH:mm");
but I got a parse error then
Try this:
String dateToParse = "9:00 am – 11:00 pm";
String splitDate[] = dateToParse.split("–");
DateFormat df = new SimpleDateFormat("h:mm a");
DateFormat outputformat = new SimpleDateFormat("HH:mm");
Date date1 = null, date2 = null;
String output1 = null, output2 = null;
try {
date1 = df.parse(splitDate[0].trim());
date2 = df.parse(splitDate[1].trim());
} catch (ParseException e) {
e.printStackTrace();
}
output1 = outputformat.format(date1);
output2 = outputformat.format(date2);
System.out.println("Output: " + output1 + " – " + output2);
Go object-oriented and use java.time
Don’t convert your interval from one string format to another. Design an Interval class for storing and manipulating your time intervals. I suggest that you include a convenience constructor that accepts a string and a toString method that produces your desired format.
I furthermore recommend that you use java.time, the modern Java date and time API, for your time work.
public class Interval {
private static final String middlePart = " – ";
private static final DateTimeFormatter amPmFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("h:mm a")
.toFormatter(Locale.ENGLISH);
private LocalTime begin;
private LocalTime end;
public Interval(String intervalString) {
String[] timeStrings = intervalString.split(middlePart);
if (timeStrings.length != 2) {
throw new IllegalArgumentException("Improper format");
}
begin = LocalTime.parse(timeStrings[0], amPmFormatter);
end = LocalTime.parse(timeStrings[1], amPmFormatter);
}
#Override
public String toString() {
return "" + begin + middlePart + end;
}
}
To try it out:
Interval testInterval = new Interval("9:00 am – 11:00 pm");
System.out.println(testInterval);
Output is:
09:00 – 23:00
What went wrong in your code?
Date is the completely wrong class to use for your interval. The class is poorly designed and long outdated. A date represents a point in time, not a time of day and certainly not an interval of two times of day.
SimpleDateFormat — a notorious troublemaker of a class — tried to parse your string into a time of January 1, 1970 in your time zone. It should have objected because a time on that day cannot be both 9 AM and 11 PM — you were contradicting yourself. But no, SimpleDateFormat gives you one of those times, keeps its mouth shut and pretends all is well. Possibly an attempt to be nice, but if so, IMHO a completely misunderstood attempt.
Link
Oracle tutorial: Date Time explaining how to use java.time.

Parse seconds-of-day as part of a date string

I need to parse a date string which has the following format:
yyyy-MM-dd TTTTT. All pattern letters are the standard DateTimeFormatter letters, except for the TTTTT part, which is a seconds-of-day field.
As there is no pattern defined for such a field, I needed to come up with something else. My first thought was to try and parse the field as milli-of-day (A), but by using 5 A's my field is treated as the least significant characters which is... yeah, not what I want.
Is there any out-of-the box solution I could use or do I have to resort to some custom made solution (like ignoring the TTTTT field, parsing it manually and using LocalDateTime.plusSeconds() on the resulting date)?
In other words, how can I make the following test case pass?
public class DateTimeParserTest {
private static final String PATTERN = "yyyy-MM-dd TTTTT";
private static final DateTimeFormatter FORMATTER =
DateTimeFormatter.ofPattern(PATTERN);
#Test
public void testParseSecondsOfDay() throws Exception {
String input = "2016-01-01 86399";
LocalDateTime localDateTime = LocalDateTime.parse(input, FORMATTER);
assertEquals("2016-01-01T23:59:59", localDateTime.toString());
}
}
Based on your correction (leaving out the potentially ambivalent part "HH:mm") the Java-8-solution would look like:
private static final DateTimeFormatter FORMATTER =
new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd ")
.appendValue(ChronoField.SECOND_OF_DAY, 5)
.toFormatter();
well it may not be what what you are looking, but i hope it helps
private static final String PATTERN = "yyyy-MM-dd HH:mm:ss"; //MODIFICATION HERE
private static final DateTimeFormatter FORMATTER =
DateTimeFormatter.ofPattern(PATTERN);
#Test
public void testParseSecondsOfDay() throws Exception {
String input = "2016-01-01 00:00:86399";
int lastIndexOf = input.lastIndexOf(':');
CharSequence parsable = input.subSequence(0,lastIndexOf)+":00";
CharSequence TTTTPart = input.subSequence(lastIndexOf+1, input.length());
LocalDateTime localDateTime = LocalDateTime.parse(parsable, FORMATTER);
Calendar calendar = Calendar.getInstance(); // gets a calendar using the default time zone and locale.
calendar.set(
localDateTime.getYear(),
localDateTime.getMonth().ordinal(),
localDateTime.getDayOfMonth(),
localDateTime.getHour(),
localDateTime.getMinute(),
0);
calendar.add(Calendar.SECOND, Integer.parseInt(TTTTPart.toString()));
StringBuilder toParse = new StringBuilder();
toParse.append(calendar.get(Calendar.YEAR) /* It gives 2016 but you what 2016, why */-1);
toParse.append("-").append(calendar.get(Calendar.MONTH) + 1 < 10 ? "0" : "")
.append(calendar.get(Calendar.MONTH)+1);
toParse.append("-").append(calendar.get(Calendar.DAY_OF_MONTH) < 10 ? "0" : "")
.append(calendar.get(Calendar.DAY_OF_MONTH));
toParse.append(" ").append(calendar.get(Calendar.HOUR_OF_DAY) < 10 ? "0" : "")
.append(calendar.get(Calendar.HOUR_OF_DAY));
toParse.append(":").append(calendar.get(Calendar.MINUTE) < 10 ? "0" : "")
.append(calendar.get(Calendar.MINUTE));
toParse.append(":").append(calendar.get(Calendar.SECOND) < 10 ? "0" : "")
.append(calendar.get(Calendar.SECOND));
localDateTime = LocalDateTime.parse(toParse, FORMATTER);
//Why 2015 and not 2016?
assertEquals("2015-01-01T23:59:59", localDateTime.toString());
}
it bugs me with is 2015 and not 2016, be aware that the solution is hammered to give you 2015 instead of 2016.
I'm still using Joda and no java8, but there it would be
Chronology lenient = LenientChronology.getInstance(ISOChronology.getInstance());
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:sssss").withChronology(lenient);
DateTime dateTime = DateTime.parse("2016-01-01 00:00:86399", FORMATTER);
assertEquals("2016-01-01T23:59:59", dateTime.toLocalDateTime().toString());
Maybe you can obtain the same behavior using:
DateTimeFormatter formatter =
DateTimeFormatter.ISO_LOCAL_DATE.withResolverStyle(ResolverStyle.LENIENT);

trying to parse/formate date with timezone using joda-time/java

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

Fast way to parse a Long date into Month-Day-Year String

How do you parse a Long date like: 1366222239935 into a String of space-separated Month-Day-Year? Like into "Apr 18 2013"
Passing it on a java.util.Date and to a String will give a String of date which contains so many info that I don't need for rendering in my GWT application.
Need to do this style since I will be passing the result into 3 <span> elements; so actually the space-separated date will be split into parts:
Month
Day
Year
As gwt won't support SimpleDateFormat
instead use Gwt DateTimeFormat
DateTimeFormat f = DateTimeFormat.getFormat("dd-MMM-yyyy");
String datestring =f.format(dateGeneratedbyLong);
And make sure the DateTimeFormat import also which you can use both client and server side .
There is another class with same name but package is different which is client(restricts you to use on client side only )
try to use SimpleDataFormat check http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html>
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");
String dateAsString = simpleDateFormat.format(new Date());
You could convert it to a Date and then manually build your String like this.-
Date date = new Date(timeInMils);
String res = date.get(Calendar.MONTH) + " " +
date.get(Calendar.DAY_OF_MONTH) + " " +
date.get(Calendar.YEAR);
That Long number is simply the number of milliseconds since the JavaScript epoch (1/1/1970 at midnight, UTC time). So, instead of parsing it, use the constructor for the Date object:
var myDate = new Date(1366222239935);
alert(myDate);
That will show "Wed Apr 17 2013 11:10:39 GMT-0700 (Pacific Daylight Time)". I am in PST, but it will default to whatever timezone you have in your locale settings.
Inside a GWT app in Java, simply do:
Date date=new Date(1366222239935);
Then you can use SimpleDateFormat to render it as "dd/MM/yy".
See http://www.w3schools.com/jsref/jsref_obj_date.asp
Do like this
Date d = new Date();
d.setTime(1366222239935l);
System.out.println(d);
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd yyyy");
try {
System.out.println(sdf.format((d)));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long diff = 1366222239935l;
Date date = new Date(diff);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
System.out.println(sdf.format(date));

Java date format real simple

how would you write te date if i have a date and all i want is the month and the day like this (mm/dd) and then turn the month like this July, 08
Let me see if I understood well.
You have a date like "07/08" and you want "July, 08"?
You could try SimpleDateFormat
import java.text.SimpleDateFormat;
import java.text.ParseException;
class Test {
public static void main( String [] args ) throws ParseException {
SimpleDateFormat in = new SimpleDateFormat("MM/dd");
SimpleDateFormat out = new SimpleDateFormat("MMMM, dd");
System.out.println( out.format( in.parse("07/08") ) );
// Verbose
//String input = "07/09";
//Date date = in.parse( input );
//String output = out.format( date );
//System.out.println( output );
}
}
Use:
Format formatter = new SimpleDateFormat("MMMM, dd");
String s = formatter.format(date);
Formatting a Date Using a Custom Format
The SimpleDateFormat is your friend here. If you already have a java.util.Date object, just format it using the desired pattern (refer to the javadoc for details on date and time patterns):
SimpleDateFormat out = new SimpleDateFormat("MMMM, dd");
String s = out.format(date); // date is your existing Date object here
(EDIT: I'm adding some details as the original question is unclear and I may have missed the real goal.
If you have a String representation of a date in a given format (e.g. MM/dd) and want to transform the representation, you'll need 2 SimpleDateFormat as pointed out by others: one to parse the String into a Date and another one to format the Date.
SimpleDateFormat in = new SimpleDateFormat("MM/dd");
Date date = in.parse(dateAsString); // dateAsString is your String representation here
Then use the code snippet seen above to format it.)
the month and the day like this (mm/dd) and then turn the month like this July, 08
So you want to convert MM/dd to MMMM, dd? So you start with a String and you end up with a String? Then you need another SimpleDateFormat instance with the first pattern.
String dateString1 = "07/08";
Date date = new SimpleDateFormat("MM/dd").parse(dateString1);
String dateString2 = new SimpleDateFormat("MMMM, dd").format(date);
System.out.println(dateString2); // July, 08 (monthname depends on locale!).

Categories

Resources