please tell me how to parse this date: "29-July-2012"
I try:
new SimpleDateFormat("dd-MMM-yyyy");
but it doesn't works. I get the following exception:
java.text.ParseException: Unparseable date: "29-July-2012"
You need to mention the Locale as well...
Date date = new SimpleDateFormat("dd-MMMM-yyyy", Locale.ENGLISH).parse(string);
In your String, the full format is used for month, so according to http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html you should be using MMMM as suggested in Baz's comment.
The reason for this can be read from the API docs.
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#month states that for month it will be interpreted as text if there are more than 3 characters and
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#text states that the full form (in your case 'July' rather than 'Jul') will be used for 4 or more characters.
Try this (Added Locale.ENGLISH parameter and long format for month)
package net.orique.stackoverflow.question11815659;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class Question11815659 {
public static void main(String[] args) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy",
Locale.ENGLISH);
System.out.println(sdf.parse("29-July-2012"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Use the split() function with the delimiter "-"
String s = "29-July-2012";
String[] arr = s.split("-");
int day = Integer.parseInt(arr[0]);
String month = arr[1];
int year = Integer.parseInt(arr[2]);
// Now do whatever u want with the day, month an year values....
Create a StringTokenizer. You first need to import the library:
import Java.util.StringTokenizer;
Basically, you need to create a delimeter, which is basically something to seperate the text. In this case, the delimeter is the "-" (the dash/minus).
Note: Since you showed the text with quotations and said parse, i'm assuming its a string.
Example:
//Create string
String input = "29-July-2012";
//Create string tokenizer with specified delimeter
StringTokenizer st = new StringTokenizer(input, "-");
//Pull data in order from string using the tokenizer
String day = st.nextToken();
String month = st.nextToken();
String year = st.nextToken();
//Convert to int
int d = Integer.parseInt(day);
int m = Integer.parseInt(month);
int y = Integer.parseInt(year);
//Continue program execution
Related
I'm developing an Android app that gets the date from the internet. What I have is a complete date format like this one : 2020-06-13T16:21:15.239920+02:00. I want to get the day of the month (which is 13 in this case).
If you are using at least API level 26, then you can use ZonedDateTime class as your string uses the default format that is understood by that class.
ZonedDateTime zdt = ZonedDateTime.parse("2020-06-13T16:21:15.239920+02:00");
int d = zdt.getDayOfMonth();
Alternatively, if the format is constant, simply use method substring()
String dd = "2020-06-13T16:21:15.239920+02:00".substring(8, 10);
If the format is not constant, I would suggest either regular expression or combining ZonedDateTime with DateTimeFormatter
Your date/time string complies with DateTimeFormatter.ISO_OFFSET_DATE_TIME. You can use java.time API to get the day of the month as shown below:
import java.time.OffsetDateTime;
public class Main {
public static void main(String[] args) {
String dateTimeStr = "2020-06-13T16:21:15.239920+02:00";
OffsetDateTime odt = OffsetDateTime.parse(dateTimeStr);
int day = odt.getDayOfMonth();
System.out.println(day);
}
}
Output:
13
If you can not use Java SE 8 Date and Time, check ThreeTenABP and also How to use ThreeTenABP in Android Project.
Its always a bad idea to split a string and extract data becuase the string will change to some other value once the date , month or any part of the date string changes and the string indexing will change
So use DateTimeFormatter
import java.time.MonthDay;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
public class SDF {
public static void main(String[] args) {
final TemporalAccessor parse = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSxxx")
.parse("2020-06-13T16:21:15.239920+02:00");
int dayOfMonth = MonthDay.from(parse).getDayOfMonth();
System.out.println(dayOfMonth);
}
}
There should be a method getDayOfMonth() available on this variable
private int parseDate(ZonedDateTime date) {
int day = date.getDayOfMonth();
return day;
}
You can use String split. Just take this whole format of date and put it into String and then create a new String Array String[] array= str.split("[-T]"); and then you can get result from array[2].
String str = "2020-06-13T16:21:15.239920+02:00";
String[] array= str.split("[-T]");
System.out.println("OUTPUT: " + array[2]);
Output: 13
String str = "2020-06-13T16:21:15.239920+02:00";
String substr = "";
// prints the substring after index 7(8 includes) till index 9(10 excludes)
substr = str.substring(8, 10);
This question already has answers here:
How to convert a String of format yyyymmdd to LocalDate in JodaTime [duplicate]
(1 answer)
Change date format in a Java string
(22 answers)
Good way to convert integer YYYYMMDD into java.util.Date with local time zone
(4 answers)
Closed 3 years ago.
I am trying to process the data from a weather station. I simply want to process and print (for now) the minimum and maximum temperatures each day starting from 2000/01/01 until today 2019/12/12. The weather station gives me the date in an integer yyyymmdd like 20191212 or 20030317. I store this, alongside the minimum and maximum temperatures in an integer array, of about 21000 rows long... I want the date to be displayed in yyyy/mm/dd, like 2019/12/12 or 2003/03/17. How exactly do I go about doing this?
This is my code
import java.io.*;
public class Main {
public static void main(String args[]) {
int rowAmount = 7152; //the amount of rows in the document
int[] temperatures = new int[rowAmount*3]; //makes an array 3 times the size of rowAmount, to fit date, min temp and max temp.
try {
BufferedReader br = new BufferedReader(new FileReader("D:\\20002019minmaxtempbilt.txt")); // Makes the filereader
String fileRead = br.readLine(); // reads first like
int counter = 0; //sets a counter
while (fileRead != null) { // loops until the file ends.
String[] tokenize = fileRead.split(","); //splits the line in 3 segements, date, min temp and max temp. And stores them in following variables
int tempDate = Integer.parseInt(tokenize[0]);
int tempMin = Integer.parseInt(tokenize[1]);
int tempMax = Integer.parseInt(tokenize[2]);
//adds the values to the array
temperatures[counter] = tempDate;
counter++;
temperatures[counter] = tempMin;
counter++;
temperatures[counter] = tempMax;
}
// close file stream
br.close();
}
catch (FileNotFoundException fnfe)
{
System.out.println("file not found");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
// Displays the entire array, formatted by date neatly, hopefully.
for(int i = 0; i<rowAmount; i =+ 3) {
int tempDate = temperatures[i];
int tempMin = temperatures[i+1];
int tempMax = temperatures[i+2];
drawLine(tempDate, tempMin, tempMax);
}
}
public static void drawLine(int tempDate, int tempMin, int tempMax) {
/*This is where I get stuck. I need to convert tempDate from an int yyyymmdd to either
3 separate integers representing year, month and day; or I need to convert it to a
string that can be printed out yyyy/mm/dd.*/
System.out.printf("");
}
}
Since your date is a String to start with I see no reason to convert it to an Integer first. Using the more current java.time package you can use one formatter to convert from a String to LocalDate and then another to convert back to a String with the right format,
DateTimeFormatter inFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate date = LocalDate.parse(tokenize[0], inFormatter);
DateTimeFormatter outFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String outStr = outFormatter.format(date);
Since DateTimeFormatter is costly to initialise I would recommend you create both of them before the loop you have for reading the file.
Another way: if the integer value representing the date is stored in an int called date (example value: 20191212), then
int day = date % 100;
int month = (date/ 100) % 100;
int year = date / 10000;
then you can use a Formatter to format the string output that you want.
A problem is that an integer of 20191212 really doesn't represent a date.
I would recommend NOT transforming tempDate into an integer and leaving it as a string.
Edit
Here is an example that uses the Java 8 time package classes: LocalDate, DateTimeFormatter, and DateTimeFormatterBuilder:
package stackoverflow;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
public class ParseStringDate {
public static void main(String... args) {
String dateString = "20191231";
DateTimeFormatter dateTimeFormatterParser = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate localDate = LocalDate.parse(dateString, dateTimeFormatterParser);
System.out.println(localDate);
DateTimeFormatter dateTimeFormatterPrinter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
System.out.println(localDate.format(dateTimeFormatterPrinter));
dateTimeFormatterPrinter = new DateTimeFormatterBuilder()
.appendPattern("yyyy")
.appendLiteral("/")
.appendPattern("MM")
.appendLiteral("/")
.appendPattern("dd").toFormatter();
System.out.println(localDate.format(dateTimeFormatterPrinter));
}
}
Here is an example that uses SimpleDateFormat:
package stackoverflow;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormattingFromString {
public static void main(String... args) throws Exception {
String tempDate = "20191212";
SimpleDateFormat sdf1 = new SimpleDateFormat("YYYYmmdd");
Date date = sdf1.parse(tempDate);
// Now format the above date as needed...
SimpleDateFormat sdf2 = new SimpleDateFormat("YYYY/mm/dd");
System.out.println(sdf2.format(date));
}
}
As pointed out in the comments, SimpleDateFormat and the Date classes are not super great to work with. They are mutable and therefore not thread safe. The new java.time package classes are immutable and therefore thread safe. The new classes are also easier to do date math with and comparisons.
I'd recommend using a DateFormat object, taking advantage of the parse(String) and format(Date) methods.
I am new to Java. I am retrieving my first column from database in a String Array which represents data as:
2014-09-01 10:00:00.000
Now I want to display only time as:
10:00:00
How to do it?
My code to retrieve my Column is:
public String[] getChartTime() throws SQLException {
List < String > timeStr = new ArrayList < String > ();
String atime[] = null;
getConnection();
try {
con = getConnection();
String sql = "exec vcs_gauge #gauge_name=?,#first_rec_time=?,#last_rec_time=?";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("date is " + df.format(currentDate));
clstmt = con.prepareCall(sql);
clstmt.setString(1, "vs3_bag");
clstmt.setString(2, "2014-09-01 10:00:00");
clstmt.setString(3, "2014-09-01 11:00:00");
clstmt.execute();
rs = clstmt.getResultSet();
while (rs.next()) {
// Just get the value of the column, and add it to the list
timeStr.add(rs.getString(1));
}
} catch (Exception e) {
System.out.println("\nException in Bean in getDbTable(String code):" + e);
} finally {
closeConnection();
}
// I would return the list here, but let's convert it to an array
atime = timeStr.toArray(new String[timeStr.size()]);
for (String s: atime) {
System.out.println(s);
}
return atime;
}
Use SimpleDateFormat:
java.util.Date date = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(date));
If you have the date as a String, you can parse it to a java.util.Date in a step before:
SimpleDateFormat sdf = new SimpleDateFormat("YOUR_DATE_PATTERN");
Date date = sdf.parse(string);
Use patterns according to https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
If I have understood the question correctly 2014-09-01 10:00:00.000 is in a string and 10:00:00 has to be extracted from that. Given below is my solution.
First split the string with space as the delimiter.
Then from that take the second part of the string.
After that split the string again using . as the delimiter and take the first sting from that.
The above things are done using the line.
str.split("\\s")[1].split("\\.")[0];
COMPLETE CODE
String str = new String("2014-09-01 10:00:00.000");
String time = str.split("\\s")[1].split("\\.")[0];
System.out.print(time);
OUTPUT
10:00:00
For more details check the links given below:
String.split().
Patterns
Refer official Java docs here
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDate {
public static void main(String[] args){
DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss a");
Date date = new Date();
String time=dateFormat.format(date);
System.out.println(time);
}
}
I got it,just use substring() as
while(rs.next()) {
// Just get the value of the column, and add it to the list
timeStr.add(rs.getString(1).substring(11,16));
}
Well, i'm trying to read a string with scanner in the same line. For exapme ,i want to read: Monday 12 December 2013 and this needs to be put in a String variable so as to help me print it.
In my code there is this:
sale.setDate(sc.next());
with the command sc.next() i can't put a date in the form i mentioned but only in a form like: mmddyy or mm/dd/yyyy
How can i read a whole string like "Monday 12 December 2013 " ?
There is a confusion for me about sc.next sc.nextLine etc..
For scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
The next() and hasNext() methods first skip any input that matches the delimiter pattern, and then attempt to return the next token. nextLine advances this scanner past the current line and returns the input that was skipped.
Use a date DateFormat to parse string to date; I suppose setDate expects a Date
Scanner scanner = new Scanner("Monday 12 December 2013,a, other fields");
scanner.useDelimiter(",");
String dateString = scanner.next();
//System.out.println(dateString);
DateFormat formatter = new SimpleDateFormat("EEEE dd MMM yyyy");
Date date = formatter.parse(dateString);
//System.out.println(date);
sale.setDate(sc.next());
Even i faced the same issue but after that able to resolve with below mentioned code. Hope it helps.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
public class Datinput {
public static void main(String args[]) {
int n;
ArrayList<String> al = new ArrayList<String>();
Scanner in = new Scanner(System.in);
n = in.nextInt();
String da[] = new String[n];
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(false);
Date date[] = new Date[n];
in.nextLine();
for (int i = 0; i < da.length; i++) {
da[i] = in.nextLine();
}
for (int i = 0; i < da.length; i++) {
try {
date[i] = sdf.parse(da[i]);
} catch (ParseException e) {
e.printStackTrace();
}
}
in.close();
}
}
Another way to do this is by utilizing LocalDateTime and DateTimeFormatter from Java 8. Found this example here:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(yyyy-MM-dd HH:mm:ss.SSS);
LocalDateTime dateTime = LocalDateTime.parse(s.next(), formatter);
System.out.println(dateTime.format(formatter));
Check the link for an in-depth explanation!
Try this..
public void readDate() throws Exception{
String dateFormat = "dd/MM/yyyy";
Scanner scanner = new Scanner(System.in);
setDate(new SimpleDateFormat(dateFormat).parse(scanner.nextLine()));
}
public void setDate(Date date){
// do stuff
}
chage the dateFormat as you want..
You have to use nextLine to fetch words with intermediate spaces.
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Scanner sc=new Scanner(System.in);
System.out.println("enter string for c");
String c=sc.next();
System.out.println("c is "+c);
System.out.println("enter string for d");
String d=sc.next();
System.out.println("d is "+d);
OUTPUT:
enter string for c
abc def
c is abc
enter string for d
d is defabc def|
in the first case abc |def //cursor stays after c
in the second case abc def| //cursor stays after for
I found this question interesting but there is not a fully correct answer, so here is a simple solution to easily read and parse a Date form the Scanner.
The best approch would be to create a method that would do it for you, since Scanner is final, we can only do a toolbox instead of a subclass. But this would be easy to use :
public static Date readDate(Scanner sc, String format){
return new SimpleDateFormat(format).parse(sc.nextLine());
}
This would accept the format and the Scanner, don't manage it here because it would be messy to open a Scanner without closing it (but if you close it, you can't open it again).
Scanner sc = new Scanner(System.in);
ToolBox.readDate(sc, "YYYY-MM-DD");
ToolBox.readDate(sc, "YYYY-MM-DD HH:mm:ss");
ToolBox.readDate(sc, "YYYY-MM-DD");
sc.close();
This could be improved by not recreating a SimpleDateFormat each time but a Scanner is not called that much (you are limit by the user inputs) so this is not that important.
try this one
final Scanner sc = new Scanner(System.in);
final String timeString = sc.next();
final LocalTime time = LocalTime.parse(timeString);
I am getting a date in this format:
2011-05-23 6:05:00
How can I obtain only 2011-05-23 from this string?
You could just take the index of the first space and use substring:
int firstSpace = text.indexOf(' ');
if (firstSpace != -1)
{
String truncated = text.substring(0, firstSpace);
// Use the truncated version
}
You'd need to work out what you wanted to do if there weren't any spaces.
However, if it's meant to be a valid date/time in a particular format and you know the format, I would parse it in that format, and then only use the date component. Joda Time makes it very easy to take just the date part - as well as being a generally better API.
EDIT: If you mean you've already got a Date object and you're trying to format it in a particular way, then SimpleDateFormat is your friend in the Java API - but again, I'd recommend using Joda Time and its DateTimeFormatter class:
DateTimeFormatter formatter = ISODateTimeFormat.date();
String text = formatter.print(date);
Using SimpleDateFormat:
parser = new SimpleDateFormat("yyyy-MM-dd k:m:s", locale);
Date date;
try {
date = (Date)parser.parse("2011-05-23 6:05:00");
} catch (ParseException e) {
}
formatter = new SimpleDateFormat("yyyy-MM-dd");
s = formatter.format(date);
Also:
http://www.exampledepot.com/egs/java.text/FormatDate.html
Standard way would be use of SimpleDateFormat
You can also accomplish it using String operation as follows
String result = str.substring(0,str.indexOf(" "));
You can use -
String arg="2011-05-23 6:05:00";
String str=arg.substring(0,arg.indexOf(" "));
Here you go:
import java.*;
import java.util.*;
import java.text.*;
public class StringApp {
public static void main(String[] args)
{
String oldDate = "2011-05-23 6:05:00";
String dateFormat = "yyyy-MM-dd";
try {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar cl = Calendar.getInstance();
cl.setTime(sdf.parse(oldDate));
String newDate = sdf.format(cl.getTime());
System.out.println(newDate);
}
catch (ParseException ex) {
}
}
}
Well an ineffective, but brute force method would be to say
String s = "2011-05-23 6:05:00";
String t = s.substring(0,s.length-7);
Or whatever the case should be
str = "2011-05-23 6:05:00"
str = str.substring(0,str.indexOf(" "));
Simplest way :
String str="2011-05-23 6:05:00";
str =str.subString(0,10);
Lots of answers, but no one had used regexp so far, so I just had to post an answer with regexp.
String date = "2011-05-23 6:05:00";
System.out.println(date.replaceFirst("\\s.*", ""));
Another answer which uses a regex.
String dateTime = "2011-05-23 6:05:00";
String date = dateTime.split(" ")[0];