Unexpected value converting String date into epoch time? - java

The below gives: 1475020875000. When I convert this epoch back to a human readable timestamp, I get: Wed, 28 Sep 2016 00:01:15 GMT, which is different from the initial date?
String date = "2016-09-27 20:01:15.0";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long epoch = df.parse(date).getTime();
System.out.println(epoch);

You should specify Timezone for both input and output. You can use "z" to instantiate SimpleDateFormat and setTimeZone before using format method:
package stackoverflow;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Programa {
public static void main(String[] args) throws ParseException {
String date = "2016-09-27 20:01:15 GMT";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
long epoch = df.parse(date).getTime();
System.out.println(epoch);
Date d = new Date(epoch);
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String out = df.format(d);
System.out.println(out);
}
}
For available Timezones, try TimeZone.getAvailableIDs()

Worked fine here:
package stackoverflow;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Programa {
public static void main(String[] args) throws ParseException {
String date = "2016-09-27 20:01:15.0";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long epoch = df.parse(date).getTime();
System.out.println(epoch);
Date d = new Date(epoch);
String out = df.format(d);
System.out.println(out);
}
}

You certainly forgot to consider the Timezone to use. If you do not define it, the default (from the JVM) is taken, and can for example differ depending on your server.

Try LocalDateTime
String date = "2016-09-27 20:01:15";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long epoch = df.parse(date).getTime();
System.out.println(epoch);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
LocalDateTime ld = LocalDateTime.parse(date, formatter);
long epoch2 = ld.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
System.out.println(epoch2);
Instant in = Instant.ofEpochMilli(epoch2);
LocalDateTime ldt = LocalDateTime.ofInstant(in, ZoneId.systemDefault());
System.out.println(ldt);
output
1474986675000
1474986675000
2016-09-27T20:01:15

Related

Convert String to epoch

I have a string - 20180915 in format yyyyMMdd
I need to get epoch milli seconds for this date, answer for 20180915 should be 1537012800000
I was able to do this using following function -
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public static void main(String args[]) throws ParseException {
String myDate = "2018-09-15 12:00:00";
LocalDateTime localDateTime = LocalDateTime.parse(myDate,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") );
System.out.println(localDateTime);
long millis = localDateTime
.atZone(ZoneOffset.UTC)
.toInstant().toEpochMilli();
System.out.println(millis);
}
The problem I am facing is -
I am passing String as "2018-09-15 12:00:00" but my input is "20180915".
I am unable to find good way to convert "20180915" to "2018-09-15 12:00:00"
How can i achieve this ?
Answer -
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
public static Long getMillisForDate(String date) {
return LocalDateTime
.of(LocalDate.parse(date, formatter), LocalTime.NOON)
.atZone(ZoneOffset.UTC)
.toInstant().toEpochMilli();
}
You can make the DateTimeFormatter do all the work, which is especially useful if you need to parse multiple dates, as it reduces the number of intermediate parsing steps (and objects created):
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
.appendPattern("uuuuMMdd")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 12)
.toFormatter()
.withZone(ZoneOffset.UTC);
String input = "20180915";
long epochMilli = OffsetDateTime.parse(input, fmt).toInstant().toEpochMilli();
System.out.println(epochMilli); // prints: 1537012800000
You can replace OffsetDateTime with ZonedDateTime. Makes no difference to the result.
Parse the date with proper mask "yyyyMMdd"
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date date = format.parse("20180915");
long epochs = date.getTime();

How to split the given format into date and time in android

Given Format:
2017-03-08 13:27:00
I want to spilt it into 2 strings
1 for date and 1 for time
for
E.g.
08-03-2017
13:27:00
First if your date in String format then Parse it to Date and then try it.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date today = new Date();
DateFormat timeFormat = SimpleDateFormat.getTimeInstance();
DateFormat dateFormat = SimpleDateFormat.getDateInstance();
timeFormat.format(today);
dateFormat.format(today);
System.out.println("Time: " + timeFormat.format(today));
System.out.println("Date: " + dateFormat.format(today));
}
}
Output:
Time: 1:25:31 AM
Date: 31 Mar, 2017
Hope this help !
try this
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FormateDate {
public static void main(String[] args) throws ParseException {
String date_s = "2017-03-08 13:27:00";
// *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = dt.parse(date_s);
// *** same for the format String below
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Date :"+dt1.format(date));
dt1 = new SimpleDateFormat("HH:mm:ss");
System.out.println("Time :"+dt1.format(date));
}
}
It gives output like this
Date :2017-03-08 Time :13:27:00
Try this :
String datetime= "2017-03-08 13:27:00";
String[] divide= datetime.split("\\s");
String date = divide[0]; //2017-03-08
String time= divide[1]; // 13:27:00

Working with SimpleDateFormat

I am trying to use simple date format to format the current time:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date now = new Date(System.currentTimeMillis());
try {
java.util.Date formattedDate = sdf.parse(now.toString());
System.out.println(formattedDate.toString());
} catch (ParseException e) {
e.printStackTrace();
}
However the output I am getting is:
Fri Oct 18 00:00:00 CDT 2013
I am trying to achieve:
2013/08/18
What am I doing wrong?
You have to use the SimpleDateFormat#format(Date date) method, which returns the date formatted in the desired way. Note that this method is inherited from DateFormat.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date now = new Date(System.currentTimeMillis());
String formattedDate = sdf.format(now);
System.out.println(formattedDate);
You are parsing your Date but not formatting it with your SimpleDateFormat. The Date#toString() method has its own output format. Use your SimpleDateFormat instead.
System.out.println(sdf.format(formattedDate));
You don't need to call parse
You don't need try/catch
Try this much simpler code:
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String formattedDate = sdf.format(new Date());
System.out.println(formattedDate);
You can try using this
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class DateFormatTest {
public static void main(String[] args) {
Date now = new Date();
// Use Date.toString()
System.out.println(now);
// Use DateFormat
DateFormat formatter = DateFormat.getInstance(); // Date and time
String dateStr = formatter.format(now);
System.out.println(dateStr);
formatter = DateFormat.getTimeInstance(); // time only
System.out.println(formatter.format(now));
// Use locale
formatter = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.FRANCE);
System.out.println(formatter.format(now));
// Use SimpleDateFormat
SimpleDateFormat simpleFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println(simpleFormatter.format(now));
}
}

how to create Date object from String value

When running through the below code I am getting an UNPARSABLE DATE EXCEPTION.
How do I fix this?
package dateWork;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateCreation {
/**
* #param args
*/
public static void main(String[] args) {
String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
Date startDate=null;
String newDateString = null;
try
{
startDate = df.parse(startDateString);
newDateString = df.format(startDate);
System.out.println(startDate);
} catch (ParseException e)
{
e.printStackTrace();
}
}
}
You used wrong dateformat for month, also you should use the same delimiter as in your date.
If you date string is of format "2013/01/03"
use the same delimiter / for the pattern "yyyy/MM/dd"
If your date string is of format "2013-01-03"
use the same delimiter '-' in your pattern "yyyy-MM-dd"
DateFormat df = new SimpleDateFormat("yyyy/mm/dd");
should be
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
From SimpleDateFormat Doc
MM---> month in an year
mm---> minutes in hour
MM instead of mm
- instead of /
ie yyyy-MM-dd as you are using - in date string
String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
you are using different pattern than what you are parsing.
either initialize this as DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
or this as String startDateString = "2013/03/26";
also look this article
pass same format string in constructor of SimpleDateFormat("yyyy-mm-dd")
as your string date is "2013-03-26"
if your date is "2013/03/26" use
SimpleDateFormat("yyyy/mm/dd")

DataTypeConvertor parseDateTime result

I am doing something like this in my program :
Calendar cal = DatatypeConverter.parseDateTime("2012-05-29T11:17:04.805-07:00");
System.out.println(cal.getTime().toString());
o/p:
Tue May 29 13:17:04 CDT 2012
Why is the result showing time of 13:17:04, in the input I have given 11:17:04 and time zone -07:00 which is pacific time zone. Should it not print out 11:17:04 ?
Your timezone - the default one when the program is running is different from the timezone given to the DatatypeConverter.parseDateTime() method and the cal.getTime().toString() method used the default timezone to format the date.
Never use Date.toString() to format Date - a Date only knows the milliseconds from the Epoch time. Instead use java.text.SimpleDateFormat like this:
SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").format(dateObject).
import java.util.Calendar;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
import javax.xml.bind.DatatypeConverter;
class TestDate
{
public static void main(String[] args)
{
Calendar cal = DatatypeConverter.parseDateTime("2012-05-29T11:17:04.805-07:00");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
df.setTimeZone(TimeZone.getTimeZone("GMT-07:00"));
String date = df.format(cal.getTime());
System.out.println(date);
}
}

Categories

Resources