How to properly format LocalTime to HH:MM? - java

I am trying to use a getter to get the LocalTime in HH:mm anytime it is called. As it stands right now it is:
private LocalTime time;
public LocalTime getTime() {
return time;
}
I would like for it to return the time in HH:mm, because as it stands right now it is HH:mm:SS.s. I am trying to mess with date time formatter, but I can't figure it out. Here is what I have:
private LocalTime time;
public LocalTime getTime() {
DateTimeFormatter formatDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalTime localFormattedTime = LocalTime.parse(time, formatDateTime);
return localFormattedTime;
}

The answer by YCF_L is correct and to-the-point. The reason why I have written this answer is I have seen similar kind of questions (why my date/time is not being printed in a custom way) being asked every now and then.
Note that LocalDate, LocalTime, LocalDateTime etc. each have their own toString()implementation and no matter what you do, whenever you print their object, their toString() method will be called and thus always their default representation will be printed. If you want these objects to be printed in a custom way, you have two options:
You get their elements (e.g. year, month and day from an object of LocalDate) and print them by arranging in your custom way.
Use a formatter class e.g. (the modern DateTimeFormatter or the legacy SimpleDateFormat) and get a string representing the date/time object in a custom way.
To make your code reusable and clean, you prefer the second approach.
The following example illustrates the same:
class Name {
private String firstName;
private String lastName;
public Name() {
firstName = "";
lastName = "";
}
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
#Override
public String toString() {
return firstName + " " + lastName;
}
}
class NameFormatter {
// Returns a name (e.g. First Last) as F. Last
public static String patternIntialsLast(Name name) {
if (name.getFirstName().length() > 1) {
return name.getFirstName().charAt(0) + ". " + name.getLastName();
}
return name.toString();
}
// Returns a name (e.g. First Last) as Last F.
public static String patternLastInitials(Name name) {
if (name.getFirstName().length() > 1) {
return name.getLastName() + " " + name.getFirstName().charAt(0) + ".";
}
return name.toString();
}
// Returns a name (e.g. First Last) as Last First
public static String patternLastIFirst(Name name) {
return name.getLastName() + ", " + name.getFirstName();
}
}
public class Main {
public static void main(String[] args) {
Name name = new Name("Foo", "Bar");
System.out.println("Default format:");
System.out.println(name);// It will always print what name.toString() returns
// If you want to print name in different formats use NameFormatter e.g.
System.out.println("\nIn custom formats:");
String strName1 = NameFormatter.patternIntialsLast(name);
System.out.println(strName1);
String strName2 = NameFormatter.patternLastIFirst(name);
System.out.println(strName2);
String strName3 = NameFormatter.patternLastInitials(name);
System.out.println(strName3);
}
}
Output:
Default format:
Foo Bar
In custom formats:
F. Bar
Bar, Foo
Bar F.
Now, go through the answer by YCF_L again and this time, you know that you have to implement your method as follows:
public String getTime() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
return formatter.format(ldt);
}
A quick demo:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Main {
// Now
static LocalDateTime ldt = LocalDateTime.of(LocalDate.now(), LocalTime.now());
public static void main(String[] args) {
System.out.println(getTime());
}
public static String getTime() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
return formatter.format(ldt);
}
}
Output:
22:23

LocalTime not have date part it have only the time part
You can't have a specific format for LocalDate, LocalTime, LocalDateTime, it use a standard format and you can't change it.
If you want a specific format then you have to use String and not LocalDate, LocalTime, LocalDateTime.

Try with this. I d
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH.mm");
LocalTime today = LocalTime.now();
String timeString = today.format(formatter); //12.38

Try something like this:
String localTimeString = "23:59:59";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
try {
TemporalAccessor ta = dtf.parse(localTimeString);
LocalTime lt = LocalTime.from(ta);
LOGGER.info("lt: {}", lt);
} catch (RuntimeException re) {
LOGGER.error("Unable to parse local time string: [{}]", localTimeString, re);
}
Consult the Java documentation on DateTimeFormatter for details on the patterns it supports.
You can also use the DateTimeFormatter to format a LocalTime back into string form, like this:
String localTimeAsString = dtf.format(lt)
LOGGER.info("LocalTime as string: {}", localTimeAsString);

Related

Convert Date format in Java

I have a Date object in DTO object:
public class TopTerminalsDTO {
private Date date;
private int volume;
private int count;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
When I get the response in Angular I get
count: 1
date: "2018-10-06T00:00:00.000+0000"
volume: 111
I want to get this date format YYYY-MM-DD HH:mm:ss in Angular.
What is the proper way to convert the Date into the DTO object? Is it better to use LocalDateTime?
It's better to use LocalDateTime object, but it will return it with a T between the date and hours. You should remove it like in the selected answer here LocalDate - How to remove character 'T' in LocalDate
U can use DateFormat to convert your desire date format.
TopTerminalsDTO tt = new TopTerminalsDTO();
tt.setDate(new Date());
String strDateFormat = "YYYY-MM-DD HH:mm:ss";
DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
String formattedDate= dateFormat.format(tt.getDate());
System.out.println(formattedDate);
As you are sending rest object to angular so u can use string field as date in DTO once covert it in desire date format.
User the Below Code.
Date myDate = new Date();
System.out.println(new SimpleDateFormat("YYYY-MM-DD HH:mm:ss").format(myDate));
LocalDate is the preferred way of many developers since it's been released in Java 8. You can format a LocalDate object the way you want by using the .format(DateTimeFormatter) method of LocalDate.
Like this example from: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
LocalDate date = LocalDate.now();
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);
Edit:
The LocalDate class doens't provide a time representation. Therefore if you like to also have time, use the LocalDateTime class. The .format() method of LocalDateTime can be used like the .format() method of LocalDate as shown above.

Deserializing with GSON converting java.sql.Date incorrectly

I am using GSON to deserialize a JSON string to a java object. The date in the JSON string is of the format:
yyyy-mm-dd
When the date is read into a java.sql.Date field in my JAVA object, the month always ends up as 01 or january! Very strange.
Here is the code for the JSON String and deserializing with GSON:
public static void main(String[] args)
{
String jsonString = "[{\"date\":\"2015-02-14\"},{\"date\":\"2015-03-15\"},{\"date\":\"2015-04-16\"}]";
Type type = new TypeToken<List<TestObject>>(){}.getType();
Gson gsonReceiver = new GsonBuilder().setDateFormat("yyyy-mm-dd").create();
List<TestObject> objectList = gsonReceiver.fromJson(jsonString, type);
for(int i=0; i < objectList.size(); i++) {
System.out.println("objectList[" + i + "] = " + objectList.get(i).toString());
}
}
And here is the code for the TestObject:
public class TestObject {
private Date date;
public TestObject(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Override
public String toString() {
return "TestObject [date=" + date + "]";
}
}
If you run this piece of code, the dates in the new object get printed out as:
objectList[0] = TestObject [date=2015-01-14]
objectList[1] = TestObject [date=2015-01-15]
objectList[2] = TestObject [date=2015-01-16]
Which is just plain weird.
I think I have set the date format like I should - anybody have any idea what is going wrong here?
The right format is
yyyy-MM-dd
mm stay for minutes. Not months.
Here is the javadoc explaining each letter that can be used in date format functions: link
Infact GSonBuilder uses the same conventions of SimpleDateFormat:
Note that this pattern must abide by the convention provided by SimpleDateFormat class. See the documentation in SimpleDateFormat for more information on valid date and time patterns.

How to get UTC time without SimpleDateFormat? [duplicate]

This question already has answers here:
How to handle calendar TimeZones using Java?
(9 answers)
Closed 8 years ago.
I'm currently working on timestamps that are converted from and to UTC. All articles that I found were based on conversion to and from String. Like this one:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));
But I wonder if there is a way to simply work with the Date instance/class or the calendar to convert the local Date into UTC and vice versa without converting it to String in between.
Read up on Joda-Time. That is a better API for such things than the java date and calendar classes
maybe this can help you:
Calendar.getInstance(java.util.TimeZone)
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
java.until.Date does not have a timezone, so there's nothing to be converted. You only see a timezone when you format the date to a string explicitly, or implicitly by using its toString method. An implicit conversion uses the local default timezone.
Internally, Date stores the date/time as a long, representing milliseconds since midnight, Jan. 1, 1970, UTC.
So, if you format a date as a string, and then parse the string back to a date, you've changed nothing at all.
So far, I could not find a perfect solution, so I had to stick to the conversion from Date to String and vice versa. Here's a little helper class that I wrote.
public class DateTimeHelper {
public static final String MYSQL_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final TimeZone timeZoneUTC = TimeZone.getTimeZone("UTC");
private Date date = new Date();
private final SimpleDateFormat format;
public DateTimeHelper(String dateTimeFormat) {
format = new SimpleDateFormat(dateTimeFormat, Locale.US);
}
public DateTimeHelper(String dateTimeFormat, String utcTimeString) {
this(dateTimeFormat);
try {
format.setTimeZone(timeZoneUTC);
Date utc = format.parse(utcTimeString);
format.setTimeZone(TimeZone.getDefault());
String local = format.format(utc);
date = format.parse(local);
} catch (ParseException e) {
// nothing
}
}
public Date getDate() {
return date;
}
public Date toUtc() {
String temp = toString();
format.setTimeZone(timeZoneUTC);
try {
return format.parse(temp);
} catch (ParseException e) {
return date;
}
}
#Override
public String toString() {
format.setTimeZone(TimeZone.getDefault());
return format.format(date);
}
public String toUtcString() {
format.setTimeZone(timeZoneUTC);
return format.format(date);
}
}
And another one that's easier to use:
public class MySqlDateTimeHelper extends DateTimeHelper {
public MySqlDateTimeHelper() {
super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT);
}
public MySqlDateTimeHelper(String utcTimeString) {
super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT, utcTimeString);
}
public static String getCurrentTimestampUtc() {
MySqlDateTimeHelper current = new MySqlDateTimeHelper();
return current.toUtcString();
}
}

Does anyone know how extract my date string & change the format?

I have a valid date in my String like this:
String strDate = "Available on 03292013";
I want to extract the date from the strDate String & change it to Available on 03/05/2015
Does anyone know how can I achieve this?
You can achieve this by doing the following steps:
First, use the regex "[^0-9]" to extract the date from your String.
Next, use the SimpleDateFormat to change the format of the extracted date from 'MMddyyyy' to
'MM/dd/yyyy'
Finally, you have to append the formatted date String value to the String “Available on”.
Please find below code for better clarity on the implementation.
package com.stackoverflow.works;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* #author sarath_sivan
*/
public class DateFormatHelper {
private static final String DD_MM_YYYY = "MMddyyyy";
private static final String DD_SLASH_MM_SLASH_YYYY = "MM/dd/yyyy";
public static void main(String[] args) {
DateFormatHelper dateFormatHelper = new DateFormatHelper();
dateFormatHelper.run();
}
public void run() {
String strDate = "Available on 03292013";
System.out.println("Input Date: " + strDate);
strDate = DateFormatHelper.getDate(strDate);
strDate = "Available on " + DateFormatHelper.formatDate(strDate);
System.out.println("Formatted Date: " + strDate);
}
public static String formatDate(String strDate) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DD_MM_YYYY);
Date date;
try {
date = simpleDateFormat.parse(strDate);
simpleDateFormat = new SimpleDateFormat(DD_SLASH_MM_SLASH_YYYY);
strDate = simpleDateFormat.format(date);
} catch (ParseException parseException) {
parseException.printStackTrace();
}
return strDate;
}
public static String getDate(String strDate) {
return strDate.replaceAll("[^0-9]", "");
}
}
Output:
Input Date: Available on 03292013
Formatted Date: Available on 03/29/2013
Hope this helps...
Try this simple and elegant approach.
DateFormat dateParser = new SimpleDateFormat("'Available on 'MMddyyyy");
DateFormat dateFormatter = new SimpleDateFormat("'Available on 'dd/MM/yyyy");
String strDate = "Available on 03292013";
Date date = dateParser.parse(strDate);
System.out.println(dateFormatter.format(date));
This should do what you want. Note that I'm just manipulating the String without any regards for what it actually contains (a date in this case).
String strDate = "Available on 03292013";
String newStr = strDate.substring(0, 15) + "/"
+ strDate.substring(15, 17) + "/" + strDate.substring(17);
System.out.println(newStr);
Result:
Available on 03/29/2013

How to parse ambiguous String into Date?

I'm trying to figure out a "simple" way of parsing a String into a Date Object.
The String can be either yyyyMMdd, yyyyMMddHHmm or yyyyMMddHHmmSS.
Currently, I'm looking at the length of the String, and creating a DateParser depending on the length. Is there a more elegant way of doing this?
Or you can pad your string with zeros:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSS") {
#Override
public Date parse(String s) throws ParseException {
return super.parse((s + "000000").substring(0, 14));
}
};
System.out.println(sdf.format(sdf.parse("20110711182405")));
System.out.println(sdf.format(sdf.parse("201107111824")));
System.out.println(sdf.format(sdf.parse("20110711")));
I would do as you are, looking at the length of the string, and creating an appropriate SimpleDateFormat instance.
SimpleDateFormat getFormatFor( String dateString ){
if ( dateString.length() == 8 ) return new SimpleDateFormat("yyyyMMdd");
if ( dateString.length() == 14 ) return new SimpleDateFormat("yyyyMMddHHmmss");
// you got a bad input...
}
NB these are not thread-safe, so you should create a new one each time.
I would use a SimpleDateFormat class, and populate the format pattern based on the length of the string. That'll work fine unless you one day have strings of the same length.
Using the examples from your question:
Formatting 11th July 2011:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date parsedDate = dateFormat.parse("20110711");
Formatting 11th July 2011 1340hrs:
dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
parsedDate = dateFormat.parse("201107111340");
Formatting 11th July 2011 1340hrs 10 seconds:
(NB. small s for seconds, capital S is for Milliseconds!)
dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
parsedDate = dateFormat.parse("20110711134010");
See the hyperlink for the full list of format pattern letters.
You could still used "specialized" parsers (as you suggested) and chain them:
For instance, you can still have a DateHourMinSecParser (for yyyyMMddHHmmSS), a DateHourMinParser (for yyyyMMddHHmm) and a DateParser (for yyyyMMdd) all of them implementing the same interface:
public interface GenericDateParser {
Date parseDate(String input) throws IllegalArgumentException;
}
e.g.
public class DateHourMinSecParser implements GenericDateParser {
...
public Date parseDate(String input) throws IllegalArgumentException {
...
}
}
but each one of these classes would actually take a parameter another GenericDateParser -- the idea being that each parser would try first to parse the date itself, if the parsing (or some internal checks -- e.g. string length) fails it would then pass it to the next parser in chain until either there are no more parsers in the chain (in which case it would throw an exception, or one of the members in the chain would return a value):
public class DateHourMinSecParser implements GenericDateParser {
private GenericDateParser chained;
public DateHourMinSecParser(GenericDateParser chained) {
this.chained = chained;
}
public Date parseDate(String input) throws IllegalArgumentException {
if( !internalChecks() ) { //chain it up
if( chained == null ) throw new IllegalArgumentException( "Don't know how to parse " + input);
}
//internal checks passed so try to parse it and return a Date or throw exception
...
}
}
and you would initialize them:
GenericDateParser p = new DateHourMinSecParser( new DateHourMinParser(new DateParser(null)) );
and then just use the top level one:
Date d = p.parse( '20110126' );
You can use a DateFormatter to parse the Date from the string.
import java.util.*;
import java.text.*;
public class StringToDate
{
public static void main(String[] args)
{
try
{
String str_date="11-June-07";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd");
date = (Date)formatter.parse(str_date);
}
catch (ParseException e)
{
System.out.println("Exception :"+e);
}
}
}
You can change the pattern however you like to reflect your needs.

Categories