JAVA Date Conversion - java

How can I convert
Wed Apr 27 17:53:48 PKT 2011
to
Apr 27, 2011 5:53:48 PM.

new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a.").format(yourDate);

You can use SimpleDateFormat or JodaTime's parser.
However it might be simple enough to write your own String parser as you are just rearranging fields.

You can do it using a mix of JDK and Joda time:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class SO5804637 {
public static void main(String[] args) throws ParseException {
DateFormat df =
new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date d = df.parse("Wed Apr 27 17:53:48 PKT 2011");
DateTimeFormatter dtf =
DateTimeFormat.forPattern("MMM dd, yyyy hh:mm:ss a");
DateTime dt = new DateTime(d);
System.out.println(dt.toString(dtf));
}
}
Note: I've included the import statements to make it clear what classes I'm using.

SimpleDateFormat sdf = new SimpleDateFormat ("MMM dd, yyyy hh:mm:ss a");
String str = sdf.format(date)

You can use SimpleDateFormat to convert a string to a date in a defined date presentation. An example of the SimpleDateFormat usage can be found at the following place: http://www.kodejava.org/examples/19.html

new java.text.SimpleDateFormat("MMM d, yyyy h:mm:ss a").format(date);
I noticed your desired output had the hour of day not prefixed by 0 so the format string you need should have only a single 'h'. I'm guessing you want the day of the month to have a similar behavior so the pattern contains only a single 'd' too.

Related

Date parsing in Java using SimpleDateFormat

I want to parse a date in this format: "Wed Aug 26 2020 11:26:46 GMT+0200" into a date. But I don't know how to do it. I tried this:
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = parser.parse(split[0]); //error line
String formattedDate = formatter.format(date);
I am getting this error: Unparseable date: "Wed Aug 26 2020 11:26:46 GMT+0200". Is my date format wrong? And if so could somebody please point me in the right direction?
I suggest you stop using the outdated and error-prone java.util date-time API and SimpleDateFormat. Switch to the modern java.time date-time API and the corresponding formatting API (java.time.format). Learn more about the modern date-time API from Trail: Date Time.
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Given date-time string
String dateTimeStr = "Wed Aug 26 2020 11:26:46 GMT+0200";
// Parse the given date-time string to OffsetDateTime
OffsetDateTime odt = OffsetDateTime.parse(dateTimeStr,
DateTimeFormatter.ofPattern("E MMM d u H:m:s zX", Locale.ENGLISH));
// Display OffsetDateTime
System.out.println(odt);
}
}
Output:
2020-08-26T11:26:46+02:00
Using the legacy API:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
// Given date-time string
String dateTimeStr = "Wed Aug 26 2020 11:26:46 GMT+0200";
// Define the formatter
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);
// Parse the given date-time string to java.util.Date
Date date = parser.parse(dateTimeStr);
System.out.println(date);
}
}
Output:
Wed Aug 26 10:26:46 BST 2020

Converting from Milliseconds to UTC Time in Java

I'm trying to convert a millisecond time (milliseconds since Jan 1 1970) to a time in UTC in Java. I've seen a lot of other questions that utilize SimpleDateFormat to change the timezone, but I'm not sure how to get the time into a SimpleDateFormat, so far I've only figured out how to get it into a string or a date.
So for instance if my initial time value is 1427723278405, I can get that to Mon Mar 30 09:48:45 EDT using either String date = new SimpleDateFormat("MMM dd hh:mm:ss z yyyy", Locale.ENGLISH).format(new Date (epoch)); or Date d = new Date(epoch); but whenever I try to change it to a SimpleDateFormat to do something like this I encounter issues because I'm not sure of a way to convert the Date or String to a DateFormat and change the timezone.
If anyone has a way to do this I would greatly appreciate the help, thanks!
java.time option
You can use the new java.time package built into Java 8 and later.
You can create a ZonedDateTime corresponding to that instant in time in UTC timezone:
ZonedDateTime utc = Instant.ofEpochMilli(1427723278405L).atZone(ZoneOffset.UTC);
System.out.println(utc);
You can also use a DateTimeFormatter if you need a different format, for example:
System.out.println( DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss").format(utc));
Try below..
package com.example;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TestClient {
/**
* #param args
*/
public static void main(String[] args) {
long time = 1427723278405L;
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(new Date(time)));
}
}
You May check this..
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(1427723278405L);
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setCalendar(calendar);
System.out.println(formatter.format(calendar.getTime()));
formatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(formatter.format(calendar.getTime()));

Java DateTime format for this one

What is the Java DateTime format for this one?
Mon Nov 26 13:57:03 SGT 2012
I want to convert this string to Date and convert it to another format like "yyyy-MM-dd HH:mm:ss".
To convert from date to string is not hard.
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
But I find no valid format to convert "Mon Nov 26 13:57:03 SGT 2012" to become date format...
=====
found solution:
DateFormat oldDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Format newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date oldDate = oldDateFormat.parse(oldTimeString);
String newDateString = newDateFormat.format(oldDate);
This will work, EEE MMM dd HH:mm:ss z yyyy
You can find examples in the javadoc of SimpleDateFormat. See http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Try SimpleDateFormat.parse() function to convert the string to Date.
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date parseDate = sdf.parse(strInput);
Watch out for the Parse Exception
Well, this code produces some output
import java.util.*;
import java.text.*;
public class Test {
public static void main(String[] args) throws ParseException {
DateFormat inputFormat = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy",
Locale.US);
DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.US);
String text = "Mon Nov 26 13:57:03 SGT 2012";
Date date = inputFormat.parse(text);
System.out.println(outputFormat.format(date));
}
}
... but it uses the default system time zone for output. It's not clear what time zone you want the result in. There's nothing in Date to store the time zone, which makes it hard to preserve the original time zone given in the text, so you'll need to decide for yourself which zone to use.
Note that I've specified Locale.US in both input and output; that's typically appropriate when you're specifying a custom format, particularly for the input which relies on month and day names.
As noted in comments, I would personally recommend using Joda Time if you possibly can for date/time work... it's a far better API than Date/Calendar. Unfortunately, Joda Time is incapable of parsing time zones - from the docs for DateTimeFormat:
Zone names: Time zone names ('z') cannot be parsed.
It's also worth noting that if there's any way you can affect the input data, moving them away from using time zone abbreviations would be a good step.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CPDateTime
{
public static void main(String[] args)
{
Calendar cal = Calendar.getInstance();
//subtracting a day
//cal.add(Calendar.DATE, -1);
cal.add(Calendar.MONTH, -1);
SimpleDateFormat prev_day = new SimpleDateFormat("dd");
SimpleDateFormat prev_month = new SimpleDateFormat("MM");
SimpleDateFormat prev_year = new SimpleDateFormat("YYYY");
String prev_day_str = prev_day.format(new Date(cal.getTimeInMillis()));
System.out.println(prev_day_str);
String prev_month_str = prev_month.format(new Date(cal.getTimeInMillis()));
System.out.println(prev_month_str);
String prev_year_str = prev_year.format(new Date(cal.getTimeInMillis()));
System.out.println(prev_year_str);
}
}

How to parse "Thu Aug 04 00:00:00 IST 2011" to "04-08-2011"?

I want to parse the date Thu Aug 04 00:00:00 IST 2011 to dd-MM-YY format like 04-08-2011. How to do this in Java?
Use the following format to parse: EEE MMM dd HH:mm:ss z yyyy with SimpleDateFormat.parse(..)
The use another SimpleDateFormat with the dd-MM-yy format, to format(..) the resultant date. Something like:
SimpleDateFormat parseFormat =
new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date date = parseFormat.parse(dateString);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yy");
String result = format.format(date);
I hope you can find the solution from the sample code below
import java.text.DateFormat;
import java.util.Date;
public class DateFormatExample
{
public static void main(String args[])
{
Date now=new Date();
System.out.println("dd/mm/yy format:" +DateFormat.getDateInstance(DateFormat.SHORT).format(now));
}
}
Now you will get your required format....

SimpleDateFormatter won't parse!

Hello I am trying to use the SimpleDateFormatter to parse the date Wed, 30 Jun 2010 15:07:06 CST
I am using the following code
public static SimpleDateFormat postedformat =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
Date newDate = new Date(posteformat.parse("Wed, 30 Jun 2010 15:07:06 CST"));
but I am getting an illegalArgumentException. Please help!
postedformat.parse() returns a Date, and there is no Date(Date) constructor.
Presumably removing the call to new Date, so you say Date newDate = poste.... will suffice
Your code fragment doesn't compile. This slight modification compiles and parses successfully:
public static void main(String[] args) throws ParseException {
SimpleDateFormat postedformat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
Date newDate = postedformat.parse("Wed, 30 Jun 2010 15:07:06 CST");
System.out.println("newDate = " + newDate);
}
This is using Java 6 on Mac OS X.
There is no java.util.Date() constructor that takes a java.util.Date as an argument
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormat {
public static SimpleDateFormat postedformat =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
public static void main(String[] args) {
try {
Date newDate = postedformat.parse("Wed, 30 Jun 2010 15:07:06 CST");
System.out.println("Date: " + newDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Outputs:
Date: Wed Jun 30 22:07:06 BST 2010
The javadoc examples shows unescaped comma but for the US locale. So either try escaping the comma (as Aaron suggested) or use the other constructor and set the Locale:
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
Another problem could be the timezone ('CST') which is deprecated on the on hand and ambigious on the other (as per javadoc of java.util.TimeZone). Test, if it works without the timezone attribute (in both the format String and the value).

Categories