Java DateTime format for this one - java

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);
}
}

Related

How can i convert String to Date when it has "TRT" in it

String sDate = "06.08.2020" // 06 day 08 month 2020 is year
This is the date i have in my txt file. I use them in JTable. To sort the table i convert them to date with this DateFormatter.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
And it does convert the string to date as this.
LocalDate date = LocalDate.parse(sDate,formatter);
//The date : Thu Aug 06 00:00:00 TRT 2020
Now i need to convert it like the first date 06.08.2020.
But i can't use date as input. Because i get it from JTable so i get it as String.
So i tryed this code.
String sDate1 = "Thu Aug 06 00:00:00 TRT 2020";// The date i get from JTable
LocalDate lastdate = LocalDate.parse(sDate1,formatter);
sDate1 = formatter.format(lastdate);
But i get an error as this Text 'Thu Aug 06 00:00:00 TRT 2020' could not be parsed at index 0.
So this cone not works fine : LocalDate lastdate = LocalDate.parse(sDate1,formatter);
I cant see where is the problem.
I cannot reproduce the behaviour you describe. The following code worked fine for me:
import java.util.*;
import java.text.*;
public class MyClass {
public static void main(String args[]) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String date = "06.08.2020";
Date date1 = sdf.parse(date);
String result = sdf.format(date1);
System.out.println("Date = " + result);
}
}
Output: Date = 06.08.2020
That being said, if at all possible you should switch to the new java.time.* API.
Where your code failed:
SimpleDateFormat sdf1=new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
String dateStr = "06.08.2020";
sdf1.parse(dateStr);
As you can see, the pattern of the SimpleDateFormat and that of the date string do not match and therefore, this code will throw ParseException.
How to make it work?
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);
You must have already got why it worked. It worked because the pattern of the SimpleDateFormat matches with that of the dateStr string.
Can I format the Date object (i.e. date) into the original string?
Yes, just use the same format which you used to parse the original string as shown below:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);
// Display in the default format
System.out.println(date);
// Format into the string
dateStr = sdf.format(date);
System.out.println(dateStr);
A piece of advice:
I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time.
Using the modern date-time API:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String dateStr = "06.08.2020";
LocalDate date = LocalDate.parse(dateStr, formatter);
// Display in the default format
System.out.println(date);
// Format into the string
dateStr = formatter.format(date);
System.out.println(dateStr);
I don't see any difference using the legacy API and the modern API:
That's true for this simple example but when you will need to do complex operations using date and time, you will find the modern date-time API smart and clean while the legacy API complex and error-prone.
Demo:
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Given date-time string
String strDate = "Thu Aug 06 00:00:00 TRT 2020";
// Replace TRT with standard time-zone string
strDate = strDate.replace("TRT", "Europe/Istanbul");
// Define formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzzz yyyy");
// Parse the date-time string into ZonedDateTime
ZonedDateTime zdt = ZonedDateTime.parse(strDate, formatter);
System.out.println(zdt);
// If you wish, convert ZonedDateTime into LocalDateTime
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2020-08-06T00:00+03:00[Europe/Istanbul]
2020-08-06T00:00

SimpleDateFormat print "." for MMM format

I am trying to convert date string from one format to another using SimpleDateFormat.
Conversion works but there is a dot "." after month.
String dateStr = "04/02/1987";
DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
Date d = df1.parse(dateStr);
DateFormat df2 = new SimpleDateFormat("dd MMM yyyy");
System.out.println(df2.format(d));
Output is 04 Feb. 1987 instead of 04 Feb 1987.
What is your Locale.getDefault()?
Different output for alphanumeric date parts may be caused by the Locale the formatter is using. In most cases, the system default Locale is used if you don't specify one yourself. I don't know for sure SimpleDateFormat does so, but it seems likely.
I know that a java.time.format.DateTimeFormatter does so, see the following example which uses java.time, the modern and recommended to use datetime API:
public static void main(String[] args) {
String dateStr = "04/02/1987";
LocalDate localDate = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
System.out.println(localDate.format(DateTimeFormatter.ofPattern("dd MMM yyyy",
Locale.ENGLISH)));
System.out.println(localDate.format(DateTimeFormatter.ofPattern("dd MMM yyyy",
Locale.FRENCH)));
}
Output:
04 Feb 1987
04 févr. 1987
The output is (of course) different concerning the name of the month, but using Locale.FRENCH shows a dot after the abbreviated month name. It is possible that your system's default Locale is one that indicates an abbreviation by a dot, too, but is identical to the output format of a Locale.ENGLISH for the numeric parts and the abbreviation of the month.
Please provide Locale.ENGLISH in SimpleDateFormat constructor while creating object as shown below:
String dateStr = "04/02/1987";
DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
Date d = df1.parse(dateStr);
DateFormat df2 = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
System.out.println(df2.format(d));

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()));

I am getting java.text.ParseException

In the below code getting parsing error:please help.
DateFormat converter = new SimpleDateFormat("dd/MM/yyyy:HH:mm:ss");
converter.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat formatter = new SimpleDateFormat("E, MMM dd yyyy");
Date date = formatter.parse(converter.format(new Date()));
I will try to explain what JB Nizet and others tried in the comments. In a simplified manner to make it understandable.
A Date is nothing else but a long which represents the time since epoch and a nice toString() method. Basically.
So if you create a Date date = new Date(); it sets the date's time value to System.currentTimeMillis();, nothing more, nothing less.
The interesting thing is that the Unix time is already "in UTC (=GMT)", if you want to say so.
If you now print the date like this
Date date = new Date();
System.out.println(date);
you implicitly call date.toString();.
This toString() can be seen as follows:
public String toString() {
return new SimpleDateFormat("E MMM dd HH:mm:ss z YYYY").format(this);
}
The SimpleDateFormat uses by default YOUR timezone. But it doesn't change the value of the date at all, it just prints it in another way.
If you now want to see the date in GMT you can simply set the SimpleDateFormat yourself:
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss z YYYY");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(date));
To push it further you could now write a simple static method somewhere to print dates in specific timezones:
public static void printDate(Date date) {
printDate(date, "GMT");
}
public static void printDate(Date date, String timeZone) {
printDate(date, TimeZone.getTimeZone(timeZone));
}
public static void printDate(Date date, TimeZone timeZone) {
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss z YYYY");
sdf.setTimeZone(timeZone);
System.out.println(sdf.format(date));
}
To see what we all are talking about (that the timestamp does never change) you can print both:
public static void printDate(Date date, TimeZone timeZone) {
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss z YYYY");
sdf.setTimeZone(timeZone);
System.out.println(sdf.format(date) + " has the timestamp " + date.getTime());
}
If we now do some simple tests we see these results:
Local Time:
Sat Feb 22 16:08:12 CET 2014 has the timestamp 1393081692749
GMT:
Sat Feb 22 15:08:12 GMT 2014 has the timestamp 1393081692749
PST:
Sat Feb 22 07:08:12 PST 2014 has the timestamp 1393081692749
As you can see the times are all correct for their timezones, and the timestamp itself is always the same.
So to answer your question: Your simple new Date();, as it's already written in the comments, already achieves what you want: the Date is always in UTC (which equals GMT).

DATETIME convert

can anyone help me with converting DATETIME funtction in Java.
I retrieve the date time format from SMS headers in this format "Fri May 18 09:22:39 FJT 2012" .I want to convert it to this format "2012-05-18 09:51:42.39".Can anyone help.
Use a SimpleDateFormat for that purpose. Although I am not sure that the timezone "FJT" is known in Java. So you will maybe have to do some tricks for that.
As #Guillaume suggested, use SimpleDateFormat. Here's an example:
public String convert() throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Date output = format.parse("Fri May 18 09:22:39 FJT 2012");
Calendar outputCal = Calendar.getInstance(format.getTimeZone());
outputCal.setTime(output);
return String.format("%04d-%02d-%02d %02d:%02d:%02d",outputCal.get(Calendar.YEAR), outputCal.get(Calendar.MONTH)+1, outputCal.get(Calendar.DAY_OF_MONTH), outputCal.get(Calendar.HOUR_OF_DAY), outputCal.get(Calendar.MINUTE), outputCal.get(Calendar.SECOND));
}
Everything is hardcoded - you have to add parameters as necessary
import java.text.SimpleDateFormat;
...
String d = "Fri May 18 09:22:39 FJT 2012";
SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss ZZZ yyyy");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SS");
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // set yr time zone for output
Date date = inputFormat.parse(d);
System.out.println(outputFormat.format(date));

Categories