Getting AM/PM information from LocalDateTime instance - java

I am taking time input from user as a String in Java and then converting it to LocalDateTime object and saving it in a text file.
Problem
hh:mm a is the format in which i am taking input form user. If i enter 12:30 PM, it is saved in text file with current date as 2019-03-20T12:30 without indication of AM or PM.
Consequently, when i read it from text file, i get the date-time information without AM or PM.
Question
Why is AM or PM not saved in the text file and how can i get it from LocalDateTime instance?
Code
Following method takes input from user, converts the user input in to LocalDateTime instance and returns it which is then saved to text file as a String
private static LocalDateTime getTimeInput(String question) {
System.out.print(question);
String userInput = scanner.nextLine();
userInput = AppointmentManager.validateTimeString(userInput, question);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd h:m a");
String todaysDateString = LocalDate.now().toString();
userInput = todaysDateString + " " + userInput;
return LocalDateTime.parse(userInput, formatter);
}
validateTimeString function is used to verify that user input is in correct format
Following method saves the data to text file
private static final File file = new File("appointments_data.txt");
public static void saveAppointmentInfo(Appointment appointment, boolean appendToFile) {
try (FileWriter fw = new FileWriter(file, appendToFile);
BufferedWriter bfw = new BufferedWriter(fw)) {
String str = AppointmentDataManager.getAppointmentInfoAsString(appointment);
bfw.write(str);
bfw.newLine();
} catch (IOException ex) {
ex.printStackTrace();
}
}
getAppointmentInfoAsString method
private static String getAppointmentInfoAsString(Appointment appointment) {
StringBuilder sb = new StringBuilder();
sb.append(appointment.getPatientId())
.append(";")
.append(appointment.getStartTime())
.append(";")
.append(appointment.getEndTime())
.append(";")
.append(appointment.getDoctor().getName());
return sb.toString();
}

When you are using StringBuilder you are calling LocalDateTime.toString() when the String segment is appended. As per LocalDateTime.toString() method javadoc:
The output will be one of the following ISO-8601 formats:
uuuu-MM-dd'T'HH:mm
uuuu-MM-dd'T'HH:mm:ss
uuuu-MM-dd'T'HH:mm:ss.SSS
uuuu-MM-dd'T'HH:mm:ss.SSSSSS
uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS
You need to save LocalDateTime with custom format to get AM/PM:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd h:m a");
sb.append(appointment.getPatientId())
.append(";")
.append(appointment.getStartTime().format(formatter))
.append(";")
.append(appointment.getEndTime().format(formatter))
.append(";")
.append(appointment.getDoctor().getName());

Take a look at simple example of how to do it. Apply it accordignaly.
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("KK:mm:ss a", Locale.ENGLISH);
String now = LocalDateTime.now().format(formatter);
System.out.println(now);
}
This is only for Java 1.8 and later.
Sign Meaning Type Example
a Am/pm marker Text PM
K Hour in am/pm (0-11) Number 0

Related

Scanner not storing string as a parsed LocalDateTime correctly

When I am taking in a string variable from the scanner and parsing it to LocalDateTime in the format "yyyy-MM-dd HH:mm" the Scanner saved the input (i.e 2020-10-12 14:30) without the time. I believe the time is being saved into the next variable. However if I input 2020-10-1214:30 without the space, it saves the the variable correctly.
Below is my constructor where the object is being created and the string is being parsed into the localdatetime object.
public computerbooking(String strDAte, String ReturnDate,String computerType,String AssetTag,String StudentId ){
counter++;
this.bookingId = "Book"+counter;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
bookingDateAndTime = bookingDateAndTime.parse(strDAte,formatter);
returnDateAndTime = returnDateAndTime.parse(ReturnDate,formatter);
this.computerType = computerType;
this.AssetTag = AssetTag;
this.StudentId = StudentId;
}
How do I instruct the scanner not to read the space between the date and time to save it correctly
LocalDateTime#parse is a static function. Use LocalDateTime.parse(strDate, formatter) instead of bookingDateAndTime.parse(strDAte,formatter).
Use Scanner#nextLine to scan the full line of input. If you are using Scanner#next, it will scan only up to 2020-10-12 i.e. it will stop scanning as soon as it will come across a whitespace character after 2020-10-12.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter date and time: ");
String strDate = scanner.nextLine();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm");
LocalDateTime bookingDateAndTime = LocalDateTime.parse(strDate, formatter);
System.out.println(bookingDateAndTime);
// A custom format
String formatted = bookingDateAndTime.format(DateTimeFormatter.ofPattern("MMM dd uuuu hh:mm a"));
System.out.println(formatted);
}
}
A sample run:
Enter date and time: 2020-10-12 14:30
2020-10-12T14:30
Oct 12 2020 02:30 pm

Setting an Input with separate year, month and day

I've set an AlertDialog.builder in which there is an input, to obtain a date from the user. Currently, it's set like that:
input.setInputType(InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_NORMAL);
What I would like, isn't simply an entire line on which the user has to write. I would like a thing like
Input: __/__/____
Where the user would have to complete with
Input: 18/04/2018
And then I would get the whole thing as a string: "18-04-2018"
What can I do?
You can parse the string to LocalDate then format to desired format, or you can just replace / with -:
String input = "18/04/2018";
String outPut;
// first approach
LocalDate localDate = LocalDate.parse(input, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
outPut = localDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
// second approach
outPut = input.replaceAll("/", "-");
You have to use SimpleDateFormat which will change the format of date. have look this
public static String changeDateToTimeStamp(String date){
DateFormat inputFormat = new SimpleDateFormat("dd/mm/yyyy");
DateFormat outputFormat = new SimpleDateFormat("dd-mm-yyyy");
Date date1 = null;
try {
date1 = inputFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return outputFormat.format(date1);
}
this method will return date like "18-04-2018". Hope it will help you!

Convert String "1/1/1970" to a date object formatted as "19700101000000"?

I am writing Junit tests to verify data entered after it has been transformed into a different format. How would I convert a String like "1/1/1970" into a date object formatted like 19700101000000? I tried this:
DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = format.parse("1/1/1970");
But "1/1/1970" throws an Unparseable date ParseException. Thanks!
You must use different DateFormats to parse and to format. Right now you're taking "1/1/1970" and trying to read it with the date format "yyyyMMddHHmmss". You'll need to parse with the format MM/dd/yyyy, get out a Date, and then format it with your format "yyyyMMddHHmmss".
You need to parse using one formatter, then reformat using another. Here's code for old style, and for new java.time API built into Java 8 and later.
String input = "1/1/1970";
// Using SimpleDateFormat
Date date = new SimpleDateFormat("M/d/yyyy").parse(input);
System.out.println(new SimpleDateFormat("yyyyMMddHHmmss").format(date));
// Using Java 8 java.time
LocalDate localDate = LocalDate.parse(input, DateTimeFormatter.ofPattern("M/d/uuuu"));
System.out.println(localDate.atStartOfDay().format(DateTimeFormatter.ofPattern("uuuuMMddHHmmss")));
As Louis Wasserman indicated, format.parse the input date String to a Date object. Then use that Date object as input to another SimpleDateFormat object.
Something like this :
public class DateFormatTest {
public static void main(String[] args) {
String inputDate = args[0];
java.util.Date d = null;
java.text.DateFormat inputDateFormat = new java.text.SimpleDateFormat("MM/dd/yyyy");
java.text.DateFormat outputDateFormat = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
try {
d = inputDateFormat.parse(intputDate);
} catch (java.text.ParseException ex) {
System.err.println("something horrible went wrong!");
}
String output = outputDateFormat.format(d);
System.out.println("The input date of: " + inputDate + " was re-formatted to: " + output);
}
}
Providing "1/1/1970" as the input parameter, the output is:
The input date of: 1/1/1970 was re-formatted to: 19700101000000

How to convert string to date format

I want to convert 3/13/2014 11:38:58 AM string to date format.
I see some examples but and also implement but I don't know how to convert AM/PM to 24 hour time format.
How to make it possible ?
Use SimpleDateFormat
Date date = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a").parse(string);
Using this you can convert your date and time..
SimpleDateFormat formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm:ss a");
Date date_current = new Date();
Date date_start = null;
date_start = sdf.parse("3/13/2014 11:38:58 AM");
System.out.println("now time is.." + date_start);
Thanks..
Parsing Strings into Dates:
The SimpleDateFormat class has some additional methods, notably parse( ) , which tries to parse a string according to the format stored in the given SimpleDateFormat object. For example:
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
String input = args.length == 0 ? "1818-11-11" : args[0];
System.out.print(input + " Parses as ");
Date t;
try {
t = ft.parse(input);
System.out.println(t);
} catch (ParseException e) {
System.out.println("Unparseable using " + ft);
}
}
}

How to convert String of datetime to date using GWT?

In mysql, i have a field time_entered of type datetime (sample data: 2012-06-20 16:00:47). I also have a method, getTimeEntered(), that returns the value as String. I want to display the date in this format 2012-06-20 using DateTimeFormat from GWT.
here's my code:
String date = aprHeaderDW.getTimeEntered();
DateTimeFormat fmt = DateTimeFormat.getFormat("MM-dd-yyyy");
dateEntered.setText("" + fmt.format(date));
The problem is, the format method doesn't accept arguments as String. So if there's only a way I could convert the date from String to Date type, it could probably work. I tried typecasting but didn't work.
You should be able to just use DateTimeFormat.
Date date = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
String dateString = DateTimeFormat.getFormat("yyyy-MM-dd").format(date);
Otherwise there is a light-weight version of SimpleDateFormat that supports this pattern.
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
Hi There are two options.
The first is as it is already a string you could use a regular expression to modify the format.
The second is using a SimpleDateFormater you can parse the string to a date then back again.
For example:
public class DateMerge {
public static void main(String arg[])
{
String out = dateConvert("2012-06-20 16:00:47");
System.out.println(out);
}
public static String dateConvert (String inDate)
{
try {
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = (Date)formatter.parse(inDate);
formatter = new SimpleDateFormat("dd-MM-yyyy");
String outDate = formatter.format(date);
return outDate;
} catch (ParseException e)
{System.out.println("Exception :"+e); }
return null;
}
}
You may use like this.
String date = "2012-06-20 16:00:47";
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
String lDate=sf.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
System.out.println(lDate);
Output:
2012-06-20
After trying a lot of times I came up with a solution, based on #Keppil and adding my own code.
Here's Keppil's suggested solution for converting String datetime into Date type:
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
...but my second requirement is to display just the date like 2012-06-20. Even though I removed HH:mm:ss, it still displayed the time like this 2012-06-20 00:00:00.
Here's my final solution:
Date date = null;
String d = rs.getString(SQL_CREATION_TIME); // assigns datetime value from mysql
// parse String datetime to Date
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(d);
System.out.println("time entered: "+ date);
} catch (ParseException e) { e.printStackTrace(); }
// format the Date object then assigns to String
Format formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(date);

Categories