i have written the code for getting date-format from the seconds which is giving the correct result .But when i try to get the seconds from the date-format i am getting the wrong result. Here is the code
public class DateTimeFind
{
public static void main(String[] args){
String seconds = "1325376000";
DateTimeFind dtf = new DateTimeFind();
// Displaying correct date from the given seconds
dtf.displayDate(seconds);
String date = "Sunday, January 1, 2012 12:00,AM";
// Displaying wrong value of seconds from the given date.
dtf.displaySeconds(date);
}
private void displayDate(String seconds){
long startEndSec = Long.parseLong(seconds);
SimpleDateFormat formatter = new SimpleDateFormat(
"EEEE, MMMM d, yyyy h:mm,a", Locale.getDefault());
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateString = formatter.format(new Date(startEndSec * 1000L));
System.out.println(dateString);
}
private void displaySeconds(String startEndDateTime){
SimpleDateFormat sourceFormat = new SimpleDateFormat(
"EEEE, MMMM dd, yyyy h:mm,a");
long c = 0;
long c1 = 0;
try
{
Date t = (Date) sourceFormat.parse(startEndDateTime);
c = t.getTime() / 1000;
}
catch(ParseException e)
{
e.printStackTrace();
}
System.out.println(Long.toString(c));
}
}
You forgot to set the same TimeZone on the SimpleDateFormat used in displaySeconds() method. Add the following line:
sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Unrelated to the concrete problem, using Locale.getDefault() to treat date formats in the English is also not entirely right. Use Locale.ENGLISH instead and add it to the constructor of the SimpleDateFormat as used in the displaySeconds() method as well.
Related
I have this string: 2018-09-22 10:17:24.772000
I want to convert it to Date:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
String sdate = "2018-09-22 10:17:24.772000";
Date dateFrom = simpleDateFormat.parse(sdate);
but it shows: Sat Sep 22 10:17:24 GMT+03:30 2018
Here is what you should do instead, you are printing date object itself, you should print its format.
I will provide the code with old date api and new local date api :
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
String sdate = "2018-09-22 10:17:24.772000";
Date dateFrom = simpleDateFormat.parse(sdate);
System.out.println(dateFrom); // this is what you do
System.out.println(simpleDateFormat.format(dateFrom)); // this is what you should do
// below is from new java.time package
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
System.out.println(LocalDateTime.parse(sdate, formatter).format(formatter));
output is :
Sat Sep 22 10:30:16 EET 2018
2018-09-22 10:30:16.000000
2018-09-22 10:17:24.772000
Hope This will help you
public class Utils {
public static void main(String[] args) {
String mytime="2018-09-22 10:17:24.772000";
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSSSSS");
Date myDate = null;
try {
myDate = dateFormat.parse(mytime);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
String finalDate = timeFormat.format(myDate);
System.out.println(finalDate);
}
}
Looks to me like you have converted it to a Date. What is your desired result? I suspect what you are wanting to do is to create another Simple date format that shows your expected format and then use simpledateformat2.format(dateFrom)
I should also point out based on past experience that you should add a Locale to your simple date formats otherwise a device with a different language setting may not be able to execute this code
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS", Locale.US);
I am facing issue in Android with DateTime conversion to local Time with timezone. I am using the below method to convert to local time but i get the 'Year' and 'Time' wrong.
P.S The DateTime received is in Bangladesh Standard Time "Asia/Dhaka", "(GMT +06:00) Dhaka"
public String localToGMT(String serverDate) {
String DATE_FORMAT = "dd.mm.yyyy HH:MM";//15.06.18 6:00
String strDate = "";
///Date date = new Date();
try {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmt = null;
gmt = sdf.parse(serverDate);
strDate = sdf.format(gmt);
} catch (ParseException e) {
e.printStackTrace();
}
return strDate;
}
Input : 22.06.2018 00:00
My output : 22.06.2017 00:12
Can someone help me with this?
MM stands for month, mm stands for minutes, and you need re-set the timezone, try this:
public static void main(String[] args) throws Exception {
String serverDate = "22.06.2018 16:00";
String DATE_FORMAT = "dd.MM.yyyy HH:mm";
String strDate;
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Dhaka"));
Date gmt = sdf.parse(serverDate);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
strDate = sdf.format(gmt);
System.out.println(strDate); // 22.06.2018 10:00
}
So I'm getting some date objects from a web server, I know that the server has the time in GMT +1 (Berlin), how can I convert the date object, to the current phone timezone date object?
Most of the questions on stackoverflow are only about formatting within a timezone, but not actually converting like this.
I've tried this
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
calendar.setTime(timeFromServer);
Calendar calendar2 = new GregorianCalendar(TimeZone.getDefault());
calendar2.setTimeInMillis(calendar.getTimeInMillis());
WHen I print, calendar2.getTime().toString() and timeFromServer.toString() will be the same;
I used Joda time and it works. You can try with Joda time. This method will convert time from server to display format time below and change to the relevant local time
public static final String SERVER_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DISPLAY_POST_FORMAT = "HH:mm dd/MM/yyyy";
public static String convertDateStrToDisplayFormat(String timeFromServer) {
DateTimeFormatter serverFormatter = DateTimeFormat.forPattern(Constants.SERVER_FORMAT);
serverFormatter.withZone(DateTimeZone.forID("Europe/Berlin"));
DateTime dateTime = DateTime.parse(timeFromServer, serverFormatter);
DateTimeFormatter pointTimeFormatter = DateTimeFormat.forPattern(Constants.POINT_TIME_FORMAT);
pointTimeFormatter.withZone(DateTimeZone.forID("Europe/Berlin"));
return pointTimeFormatter.print(dateTime)
}
I use this to convert the date from the server and convert it to current phone timezone date object
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat deviceFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",Locale.ENGLISH);
deviceFormat.setTimeZone(TimeZone.getDefault());
Date utcDate ;
Date deviceDate ;
utcDate = sourceFormat.parse(event_date);
deviceDate = deviceFormat.parse(utcDate.toString());
event_date is a String that has the server date. After this you have your converted Date on deviceDate.
java.util.Date does not use timezone, so when you try to print the string representation of the following date objects using method Date#toString(), the results are the same:
calendar2.getTime().toString()
timeFromServer.toString()
In order to test the string representation correctly with timezone, you need to use SimpleDateFormat:
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
f.setTimeZone(calendar.getTimeZone());
// Date correctly printed with timezone:
System.out.println(f.parse(calendar.getTime()));
However, your conversion written in the question is correct, here's how I tested it using JUnit:
#Test
public void testDateConversion() throws ParseException {
String serverText = "2017-03-02T11:54:30.207+01:00";
SimpleDateFormat serverFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
serverFmt.setTimeZone(TimeZone.getTimeZone("GMT+1"));
Date timeFromServer = serverFmt.parse(serverText);
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT-1"));
calendar.setTime(timeFromServer);
assertEquals(2017, calendar.get(Calendar.YEAR));
assertEquals(Calendar.MARCH, calendar.get(Calendar.MONTH));
assertEquals(2, calendar.get(Calendar.DAY_OF_MONTH));
assertEquals(9, calendar.get(Calendar.HOUR_OF_DAY));
assertEquals(54, calendar.get(Calendar.MINUTE));
assertEquals(30, calendar.get(Calendar.SECOND));
assertEquals(207, calendar.get(Calendar.MILLISECOND));
SimpleDateFormat currFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
currFmt.setTimeZone(calendar.getTimeZone());
System.out.printf("server_timestamp = %d, server_date = '%s', server_str = '%s'%n",
timeFromServer.getTime(),
serverFmt.format(timeFromServer),
timeFromServer.toString());
System.out.printf("current_timestamp = %d, current_date = '%s', current_str = '%s'%n",
calendar.getTime().getTime(),
currFmt.format(calendar.getTime()),
calendar.getTime().toString());
}
Result:
server_timestamp = 1488452070207, server_date = '2017-03-02T11:54:30.207+01:00', server_str = 'Thu Mar 02 11:54:30 CET 2017'
current_timestamp = 1488452070207, current_date = '2017-03-02T09:54:30.207-01:00', current_str = 'Thu Mar 02 11:54:30 CET 2017'
See also:
SimpleDateFormat (Java Platform SE 7)
I am trying to use SimpleDateFormat.parse method to parse a date string to Date object, but it is omitting "T" in the final date that is returned. I am passing this date string 2015-04-15T12:55:07.365 and I am getting 2015-04-15 12:55:07.365 in the output. However, the desired output is 2015-04-15T12:55:07.365.
Why is "T" in the final output omitted by this line parsedDate = sdf.parse(transDate);
public static void main(String[] args)
{
try
{
final String pattern = "yyyy-MM-dd'T'hh:mm:ss.SSS"; // example 2015-04-15T12:55:07.365
final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String transDate = "2015-04-15T12:55:07.365";
Date parsedDate = sdf.parse(transDate);
System.out.println("transDate:"+transDate+", parsedDate: "+parsedDate);
}
You never get your desired output 2015-04-15T12:55:07.365
Why?
Because you are printing Date object parsedDate.Date class has it's own toString() method implementation.When you are printing the date object, it means it basically prints the toString() method implementation format.
see the Java doc for details
System.out.println(parsedDate) would give you Wed Apr 15 00:55:07 GMT 2015 which is the toString() representation of the date object.
You can use SimpleDateFormat to parse AND format dates:
SimpleDateFormat sdfParser = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
Date date = sdfParser.parse("2015-04-15T12:55:07.365");
SimpleDateFormat sdfFormatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
String formattedDate = sdfFormatter.format(date);
System.out.println(formattedDate);
// 2015-04-15T12:55:07.365
You will get desired output here.
public static void main(String args[]) {
{
try {
String transDate = "2015-04-15T12:55:07.365";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
Date date = sdf.parse(transDate);
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date d = sdf.parse(sdf.format(date));
String formattedTime = output.format(d);
System.out.println("transDate:" + transDate + ", parsedDate: " + formattedTime);
} catch (Exception e) {
}
}
}
I'm trying to convert string to date format.I trying lot of ways to do that.But not successful. my string is "Jan 17, 2012". I want to convert this as " 2011-10-17".
Could someone please tell me the way to do this? If you have any worked through examples, that would be a real help!
try {
String strDate = "Jan 17, 2012";
//current date format
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
Date objDate = dateFormat.parse(strDate);
//Expected date format
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
String finalDate = dateFormat2.format(objDate);
Log.d("Date Format:", "Final Date:"+finalDate)
} catch (Exception e) {
e.printStackTrace();
}
String format = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
Which produces this output when run in the PDT time zone:
yyyy-MM-dd 1969-12-31
yyyy-MM-dd 1970-01-01
For more info look at here
I suggest using Joda Time, it's the best and simplest library for date / dateTime manipulations in Java, and it's ThreadSafe (as opposed to the default formatting classes in Java).
You use it this way:
// Define formatters:
DateTimeFormatter inputFormat = DateTimeFormat.forPattern("MMM dd, yyyy");
DateTimeFormatter outputFormat = DateTimeFormat.forPattern("yyyy-MM-dd");
// Do your conversion:
String inputDate = "Jan 17, 2012";
DateTime date = inputFormat.parseDateTime(inputDate);
String outputDate = outputFormat.print(date);
// or:
String outputDate = date.toString(outputFormat);
// or:
String outputDate = date.toString("yyyy-MM-dd");
// Result: 2012-01-17
It also provides plenty of useful methods for operations on dates (add day, time difference, etc.). And it provides interfaces to most of the classes for easy testability and dependency injection.
Why do you want to convert string to string try to convert current time in milisecond to formated String,
this method will convert your milisconds to a data formate.
public static String getTime(long milliseconds)
{
return DateFormat.format("MMM dd, yyyy", milliseconds).toString();
}
you can also try DATE FORMATE class for better understanding.
You can't convert date from one format to other. while you are taking the date take you have take the date which ever format the you want. If you want the date in yyyy-mm-dd. You can get this by using following way.
java.util.Calendar calc = java.util.Calendar.getInstance();
int day = calc.get(java.util.Calendar.DATE);
int month = calc.get(java.util.Calendar.MONTH)+1;
int year = calc.get(java.util.Calendar.YEAR);
String currentdate = year +"/"+month +"/"+day ;
public static Date getDateFromString(String date) {
Date dt = null;
if (date != null) {
for (String sdf : supportedDateFormats) {
try {
dt = new Date(new SimpleDateFormat(sdf).parse(date).getTime());
break;
} catch (ParseException pe) {
pe.printStackTrace();
}
}
}
return dt;
}
Try this simple method:
fun getFormattedDate(strDate:String): String {
try {
val dateFormat = SimpleDateFormat("dd/mm/yyyy")//old format
val dateFormat2 = SimpleDateFormat("mm/dd/yyyy")//require new formate
val objDate = dateFormat.parse(strDate)
return dateFormat2.format(objDate)
} catch (e:Exception) {
return ""
}
}