How to convert String and date time in java - java

Hi everyone i used bootstrap date time picker to save date and time when i select the date in jsp. am getting date and time as a String in java class like this 23 January 2017 - 02:50 pm am trying to convert this to date is not working where i need to change
$(function () {
$('#datetimepicker8').datetimepicker({
startDate: new Date(),
format : 'dd MM yyyy - HH:ii p',
autoclose: 1,
}).on( 'changeDate', function(e) {
// Revalidate the date field
$('#timeTableUpdateForm').bootstrapValidator(
'revalidateField', 'examDate');
});
});
.
public class StringToDate {
public static void main(String[] args) {
SimpleDateFormat formatter =
new SimpleDateFormat("dd MMMM yyyy-HH:mm:ss a");
String dateInString = "23 January 2017 - 02:50 pm";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
}
catch( ParseException e ) {
e.printStackTrace();
}
}
}

Here is a working code:
public static void main( String[] args ) {
final SimpleDateFormat formatter =
new SimpleDateFormat( "dd MMMMM yyyy - HH:mm a", Locale.US );
final String dateInString = "23 January 2017 - 02:50 pm";
try {
final Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
}
catch( final ParseException e ) {
e.printStackTrace();
}
}
With this output :
Mon Jan 23 02:50:00 CET 2017
23 January 2017 - 02:50 AM

Two errors here:
A space is missing between year and dash - dash and hour
You are telling java to parse seconds, but you don't have seconds in your date string.
You need to change your SimpleDateFormat from
SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy-HH:mm:ss a");
To
// Added two spaces and removed seconds from format, added Locale
SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy - HH:mm a", Locale.US);
// ^ ^ ^
By changing your code this way I get this output:
Mon Jan 23 02:50:00 GMT 2017
23 January 2017 - 02:50 AM
DEMO

Related

Android time conversion

i have done code below to change time from UTC to another time zone but code is showing only UTC time.Also after formatting to source time format it shows system time zone .
private String setTimezone(String time){
sourceformatter = new SimpleDateFormat("hh:mm a, E dd MMM yyyy");
dateFormatter = new SimpleDateFormat("hh:mm a");
sourceformatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Log.e("reicievedformat",time);
Date value = null;
try {
value = sourceformatter.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
Log.d("afterfirstformat",dateFormatter.format(value));
dateFormatter.setTimeZone(TimeZone.getTimeZone("IST"));
time =dateFormatter.format(value);
Log.d("Finaltime",time);
return time;
}
Output:- Log values
E/reicievedformat: 12:36 PM, Mon 08 Oct 2018
D/afterfirstformat: 06:21 PM
D/Finaltime: 12:36 PM
As you can see I'm getting 12:36 PM, Mon 08 Oct 2018 ("UTC") and I want to convert to IST, but the final time, 12:36 PM, doesn’t seem to have been converted.
IST in java stands for "Israel Standard Time".
Use this for "Indian Standard Time"
dateFormatter.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
The date & time APIs in Java gives you headache.
I use this library by Daniel Lew.
https://github.com/dlew/joda-time-android
Try this
public static String getDateOut(String ourDate) {
try
{
//be sure that passing date has same format as formatter
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a, E dd MMM yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(ourDate);
SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm a"); //this format changeable
dateFormatter.setTimeZone(TimeZone.getTimeZone("IST"));
ourDate = dateFormatter.format(value);
}
catch (Exception e)
{
ourDate = "00-00-0000 00:00";
}
return ourDate;
}

How to parse given string format to dd-MMM-yyyy hh:mm:ss:aa?

I can get the output as Wed May 11 15:36:08 IST 2016, but how do I convert the date to a string with the required format?
Required format is: 12-05-2016 16:05:08 pm
What I tried is,
public class Test {
public static void main(String args[]) throws ParseException{
String epoche="1462961108000";
Long initialLogTime = Long.valueOf(epoche);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(initialLogTime);
Calendar fromDateTime = calendar;
Calendar toDateTime = fromDateTime;
toDateTime.add(Calendar.MINUTE, 30);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss:aa");
String datestring = String.valueOf(fromDateTime.getTime());
String datestring1 = String.valueOf(toDateTime.getTime());
System.out.println(datestring); //here output is Wed May 11 15:36:08 IST 2016
System.out.println(datestring1); // here output is Wed May 11 15:36:08 IST 2016
Date dates = dateFormat.parse(datestring);
Date date1s = dateFormat.parse(datestring1);
System.out.println(dates);
System.out.println(date1s);
}
}
The error I am getting is:
Exception in thread "main" java.text.ParseException: Unparseable date: "Wed May 11 16:05:08 IST 2016"
at java.text.DateFormat.parse(DateFormat.java:357)
at test.Test.main(Test.java:27)
You need to format your dates accordingly. This shall help you
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:aa");
System.out.println(dateFormat.format(fromDateTime.getTime()));
System.out.println(dateFormat.format(toDateTime.getTime()));
if you are using java 8, you can use
LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss:aa");
System.out.println(date.format(formatter));
Please try this
public static void main(String[] args) {
String epoche = "1462961108000";
Date date = new Date(Long.parseLong(epoche));
DateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:aa");
String strDate = sdf.format(date);
System.out.println(strDate);
}
Output
11-05-2016 15:35:08:PM
In Android, Pass String Like 11/10/2017 11:16:46 to function ConvertDateTime
public String ConvertUpdate(String strDate) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
Date d = simpleDateFormat.parse(strDate);
simpleDateFormat = new SimpleDateFormat("dd MMM yy hh:mm a");
return simpleDateFormat.format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
output
10 Nov 17 11:16 AM

Format date with SimpleDateFormat Java [duplicate]

This question already has answers here:
Java String to Date, ParseException
(4 answers)
Closed 7 years ago.
I have a date string as
"Wed Jul 01 08:16:13 PDT 2015"
I am trying to parse it with this SimpleDateFormat
SimpleDateFormat valueDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
this way:
Date parsedDate1 = valueDateFormat.parse("Wed Jul 01 08:16:13 PDT 2015");
It is giving me parse error as:
java.text.ParseException: Unparseable date: "Wed Jul 01 08:16:13 PDT 2015" (at offset 0)
How can I get a date in above simple date format from the string
Try this:
DateFormat originalFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy");
DateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = originalFormat.parse("Wed Jul 01 08:16:13 PDT 2015");
String formattedDate = targetFormat.format(date);
System.out.println(formattedDate);
I suspect you don't realy understand the consept of the SimpleDateFormat.
After you define the template with :
SimpleDateFormat valueDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
The valueDateFormat could parse Date object acording to it, it not take just a String you have and convert it. it take Date object.
Date
Your date string ("Wed Jul 01 08:16:13 PDT 2015") doesn't match your pattern ("yyyy-MM-dd hh:mm:ss")
Write correct pattern which matches date string (first goes Day of week, than month in year, etc.)
try this..
public static void main(String[] a)
{
SimpleDateFormat valueDateFormat = new SimpleDateFormat("EEE MMM yy hh:mm:ss");
try {
Date parsedDate1 = valueDateFormat.parse("Wed Jul 01 08:16:13 PDT 2015");
System.out.println(parsedDate1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
For the formats like this I created a helper method:
public Date parseString(String date) {
String value = date.replaceFirst("\\D+([^\\)]+).+", "$1");
//Timezone could be either positive or negative
String[] timeComponents = value.split("[\\-\\+]");
long time = Long.parseLong(timeComponents[0]);
int timeZoneOffset = Integer.valueOf(timeComponents[1]) * 36000; // (("0100" / 100) * 3600 * 1000)
//If Timezone is negative
if(value.indexOf("-") > 0){
timeZoneOffset *= -1;
}
//Remember that time could be either positive or negative (ie: date before 1/1/1970)
//time += timeZoneOffset;
return new Date(time);
}
It returns date object from Date string so you can format your string like this:
Date date = parseString("Wed Jul 01 08:16:13 PDT 2015");
And after that you can easily format given date variable.

How to convert string (Twitter4j format) to Java Date

I would like to extract date and year from the following string and convert it to a Data Object in Java.
Mon Jul 07 19:18:26 CEST 2014
How can I extract only date and year (in this case, 2014-07-07) from the text in a sophisticated way?
SimpleDateFormat s = new SimpleDateFormat("dd/MMM/yyyy");
String dateInString = "Mon Jul 07 19:18:26 CEST 2014";
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = s.parse(dateInString.split(" ")[2]+"/"+dateInString.split(" ")[1]+"/"+dateInString.split(" ")[5]);
System.out.println(new SimpleDateFormat("YYYY-MM-dd").format(date));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This should work for you, I splitted your String, then put it to a date format and then formatted it the way you wanted it to be, assumed you wanted the months as the second parameter after the year, if thats not the case you can simply change the 'MM' to 'dd' and the 'dd' to 'MM'.
For Java 7 or below, use a SimpleDateFormat for parsing and formatting:
Locale dateLocale = Locale.US;
SimpleDateFormat inFormat = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy", dateLocale);
Date date = inFormat.parse("Mon Jul 07 19:18:26 CEST 2014");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd", dateLocale);
System.out.println(outFormat.format(date));
Since Java 8, you can use DateTimeFormatter:
Locale dateLocale = Locale.US;
DateTimeFormatter inFormatter = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss z yyyy", dateLocale);
TemporalAccessor date = inFormatter.parse("Mon Jul 07 19:18:26 CEST 2014");
DateTimeFormatter outFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
System.out.println(outFormatter.format(date));

java does not parse for 'M dd, yyyy' date format

I want to parse date strings like "February 7, 2011" using "M dd, yyyy" format. But I get an exception.
Try this code. I ran it with two dates "November 20, 2012" and "January 4, 1957" and got this output:
arg: November 20, 2012 date: Tue Nov 20 00:00:00 EST 2012
arg: January 4, 1957 date: Fri Jan 04 00:00:00 EST 1957
It works fine. Your regex was wrong.
package cruft;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* DateValidator
* #author Michael
* #since 12/24/10
*/
public class DateValidator {
private static final DateFormat DEFAULT_FORMATTER;
static {
DEFAULT_FORMATTER = new SimpleDateFormat("MMM dd, yyyy");
DEFAULT_FORMATTER.setLenient(false);
}
public static void main(String[] args) {
for (String dateString : args) {
try {
System.out.println("arg: " + dateString + " date: " + convertDateString(dateString));
} catch (ParseException e) {
System.out.println("could not parse " + dateString);
}
}
}
public static Date convertDateString(String dateString) throws ParseException {
return DEFAULT_FORMATTER.parse(dateString);
}
}
Your parsing string is not correct as mentioned by others
To correctly parse February you need to use an english Locale or it may fail if your default Locale is not in English
DateFormat df = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH);
Date dt = df.parse("February 7, 2011");
You will want to use "MMM dd, yyyy"
SimpleDateFormat("MMM dd, yyyy").parse("February 7, 2011")
See SimpleDateFormat
Assuming you are using SimpleDateFormat, the month format is incorrect, it should be MMM dd, yyyy
MMM will match the long text format of the month:
String str = "February 7, 2011";
SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy");
Date date = format.parse(str);

Categories