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()));
Related
I tried to parse the date (3 December, 2020) with format d MMMM yyyy in Polish Locale but it is unable to parse. But why the same parsing is working fine in any other locale like english, etc. Below is the code sample which is not working. Can anyone please help on this ?
Locale loc = new Locale("pl", "PL");
String date = "3 December 2020";
SimpleDateFormat sdFormat =
new SimpleDateFormat("d MMMM yyyy", loc);
sdFormat.setLenient(false);
try {
Date d = sdFormat.parse(date);
System.out.println(d);
} catch (ParseException e) {
e.printStackTrace();
}
It seems you got confused with parsing and formatting.
Since your input date string in English, you need to use Locale.ENGLISH for parsing and you need another instance of SimpleDateFormat with Locale("pl", "PL") to format the obtained java.util.Date object with new Locale("pl", "PL").
Demo:
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[]) {
Locale loc = new Locale("pl", "PL");
String date = "3 December 2020";
SimpleDateFormat sdfForParsing = new SimpleDateFormat("d MMMM yyyy", Locale.ENGLISH);
SimpleDateFormat sdfForFormatting = new SimpleDateFormat("d MMMM yyyy", loc);
sdfForParsing.setLenient(false);
try {
Date d = sdfForParsing.parse(date);
System.out.println(d);
String localiseByPolish = sdfForFormatting.format(d);
System.out.println(localiseByPolish);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output:
Thu Dec 03 00:00:00 GMT 2020
3 grudnia 2020
I believe you already know that a date-time object stores just the date-time information*1and no formatting information. On printing, a date-time object prints the string returned by the toString implementation of its class. Also, a java.util.Date object does not represent a true date-time class as it stores just the milliseconds (e.g. new Date() object is instantiated with the number of milliseconds from January 1, 1970, 00:00:00 GMT) and when you print it, it calculates the date-time in your JVM's timezone and prints the same i.e. if your execute the following two lines at a given moment in any part of the world,
Date date = new Date();
System.out.println(date.getTime());
you will get the same number. Check this answer for a demo.
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and because of so many such hacks, they are error-prone. It is recommended to stop using them completely and switch to the modern date-time API. Learn more about the modern date-time API at Trail: Date Time.
Note: If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Using the modern date-time API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
Locale loc = new Locale("pl", "PL");
String date = "3 December 2020";
DateTimeFormatter dtfForParsing = DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.ENGLISH)
.withResolverStyle(ResolverStyle.LENIENT);
DateTimeFormatter dtfForFormatting = DateTimeFormatter.ofPattern("d MMMM yyyy", loc);
LocalDate localeDate = LocalDate.parse(date, dtfForParsing);
System.out.println(localeDate);
String localiseByPolish = localeDate.format(dtfForFormatting);
System.out.println(localiseByPolish);
}
}
Output:
2020-12-03
3 grudnia 2020
*1The modern date-time API store also the timezone information. Check Overview to learn more about these classes.
When trying to determine problems with parsing, always do the opposite, i.e. generate output, to see what the input for parsing should look like. This is a technique that is very useful for all parsing related issues, whether parsing date strings, XML documents, JSON texts, etc.
So, we try printing a date value with the given format, to see what it would expect when parsing:
Locale loc = new Locale("pl", "PL");
SimpleDateFormat sdFormat = new SimpleDateFormat("d MMMM yyyy", loc);
sdFormat.setLenient(false);
Calendar cal = Calendar.getInstance(loc);
cal.clear();
cal.set(2020, Calendar.DECEMBER, 3);
System.out.println(sdFormat.format(cal.getTime()));
In Java 7, I get 3 grudzień 2020.
In Java 8, 9, 11, and 14, I get 3 grudnia 2020.
If you want to parse 3 December 2020, then use e.g. Locale.ENGLISH.
Is there any way in java(java.util.* or Joda api ) to convert "2020-04-03 20:17:46" to "yyyy-MM-dd'T'HH:mm:ss"
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.parse("2020-04-03 20:17:46")
its giving java.text.parseException always
Just for the case you are using Java 8 or above, make use of java.time.
See this simple example:
public static void main(String[] args) {
// example datetime
String datetime = "2020-04-03 20:17:46";
// create a formatter that parses datetimes of this pattern
DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// then parse the datetime with that formatter
LocalDateTime ldt = LocalDateTime.parse(datetime, parserDtf);
// in order to output the parsed datetime, use the default formatter (implicitly)
System.out.println(ldt);
// or format it in a totally different way
System.out.println(ldt.format(
DateTimeFormatter.ofPattern("EEE, dd. 'of' MMM 'at' hh-mm-ss a",
Locale.ENGLISH)
)
);
}
This outputs
2020-04-03T20:17:46
Fri, 03. of Apr at 08-17-46 PM
Please note that this doesn't consider any time zone or offset, it just represents a date and time consisting of the passed or parsed years, months, days, hours, minutes and seconds, nothing else.
Do not use Date/Time API from java.util.* as most of them are now outdated. Use java.time API instead.
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) throws IOException {
String strDatetime = "2020-04-03 20:17:46";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsedDate = LocalDateTime.parse(strDatetime, formatter);
System.out.println(parsedDate);
}
}
Output:
2020-04-03T20:17:46
Learn more about DateTimeFormatter at https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
Could this help you? http://tutorials.jenkov.com/java-internationalization/simpledateformat.html
First you need to parse the String with the old format, you will get a Date object. Then Create a new SimpleDateFormat with your new format, then you can format the Date object.
String dateString = "2020-04-03 20:17:46";
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(dateString);
String formattedDate = output.format(date);
It do not work that way directly but if you still want to do it then, here is the process.
Create an object of SimpleDateFormat with pattern "yyyy-MM-dd HH:mm:ss")
use this to parse the string. Ultimately you are going to get date in both cases. Is there any specific reason for using T in pattern for dates which do not contain them?
Use LocalDateTime.
Timestamp timestamp = Timestamp.parse("2020-04-03 20:17:46");
LocalDateTime localDateTime = timestamp.toLocalDateTime();
System.out.println(localDateTime); // 2020-04-03T20:17:46
I want current time in millis and then to store it in 12 hour format but with this piece of code I am getting 24 hour format time.
long timeInMillis = System.currentTimeMillis();
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(timeInMillis);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy HH:mm:ss a");
dateforrow = dateFormat.format(cal1.getTime());
can anybody suggest modifications to get the desired results?
Change HH to hh as
long timeInMillis = System.currentTimeMillis();
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(timeInMillis);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd/MM/yyyy hh:mm:ss a");
dateforrow = dateFormat.format(cal1.getTime());
Note that dd/mm/yyyy - will give you minutes instead of the month.
Referring to SimpleDataFormat JavaDoc:
Letter | Date or Time Component | Presentation | Examples
---------------------------------------------------------
H | Hour in day (0-23) | Number | 0
h | Hour in am/pm (1-12) | Number | 12
I re-encounter this in the hard way as well. H vs h, for 24-hour vs 12 hour !
Yep, confirmed that simply using "hh" instead of "HH" fixed my issue, Since "hh" is for 12-Hour Format & "HH" is for 24-Hour Format.
Changed from this:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm aa");
To this:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
You can still use "HH" to store the time if you don't want to bother storing and dealing with the AM/PM. Then when you retrieve it, use "hh".
Hi I tested below code that worked fine :
long timeInMillis = System.currentTimeMillis();
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(timeInMillis);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
dateFormat.format(cal1.getTime());
There are three major problems with your code:
Using m [Minute in hour] at the place of M [Month in year].
Using H [Hour in day (0-23)] instead of h [Hour in am/pm (1-12)]. Check the documentation to learn more about these two points.
Not using Locale with SimpleDateFormat. Check Never use SimpleDateFormat or DateTimeFormatter without a Locale to learn more about it.
So, the instantiation with the correct format would be:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a", Locale.ENGLISH);
java.time
Note that the java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*, released in March 2014 as part of Java SE 8 standard library.
Solution using java.time, the modern Date-Time API:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
OffsetDateTime odt = OffsetDateTime.now(ZoneOffset.UTC);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/uuuu hh:mm:ss a", Locale.ENGLISH);
String formatted = dtf.format(odt);
System.out.println(formatted);
}
}
Here, you can use y instead of u but I prefer u to y.
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
You can try it like this
Calendar c= Calendar.getInstance();
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
String str=sdf.format(c.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
use hh in place of HH
Simply follow the code
public static String getFormatedDate(String strDate,StringsourceFormate,
String destinyFormate) {
SimpleDateFormat df;
df = new SimpleDateFormat(sourceFormate);
Date date = null;
try {
date = df.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
df = new SimpleDateFormat(destinyFormate);
return df.format(date);
}
and pass the value into the function like that,
getFormatedDate("21:30:00", "HH:mm", "hh:mm aa");
or checkout this documentation SimpleDateFormat for StringsourceFormate and destinyFormate.
See code example below:
SimpleDateFormat df = new SimpleDateFormat("hh:mm");
String formattedDate = df.format(new Date());
out.println(formattedDate);
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);
}
}
I have to write datetime in a MySQL database:
i need simple as this:
this.repes.get(parcelaIdx).setFechaCosecha(new Date());
But because the date is three hours ahead!!, so it's GMT -00, and I'm at GMT -03 (Argentina).
How can I get current and local machine date and time??
Edit: to clarify, just a little code:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class AllTimeZones{
public static void main(String args[]){
String[] AllID= TimeZone.getAvailableIDs();
Date myDate = new Date();
for(int i=0;i<AllID.length;i++)
{
System.out.println("TimeZone ["+(i+1)+"] ==>"+TimeZone.getTimeZone(AllID[i]));
System.out.println("myDate sin TimeZone:" + myDate);
DateFormat dfm = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
dfm.setTimeZone(TimeZone.getTimeZone(AllID[i]));
System.out.println("myDate con TimeZone:" + dfm.format(myDate) );
}
}
}
Date objects do not support timezones, they are just "specific instant in time". Whenever you need date along with timezone information use Calendar instead.
P.S: I would suggest whenever you write time to a database, always write in GMT/UTC format. So using new Date() will give in that format(GMT+0) already. And later when you retrieve it form DB and show to client convert it appropriately.
Here we go again. A Date doesn't have a time zone. It's an instant in time. It's only when it's displayed in a human-readable format that a timezone is used. Change the way the date is displayed. It's constructed correctly.