Converting date to long in Java - java

I have the following string 02/11/2012 23:11
Is there any way to convert this to the long 021120122311l?
I am trying to map objects to a specific position in an array based on their date created.

You can try this
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm");
Date inputDate;
try {
inputDate = simpleDateFormat.parse("02/11/2012 23:11");
System.out.println(inputDate.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
ouput:
1351878060000

you can use a SimpleDateFormat to generate it as a string without any symbol, and then parse the long value using the Long class
SimpleDateFormat s1 = new SimpleDateFormat("dd/MM/yyyy HH:mm");
SimpleDateFormat s2 = new SimpleDateFormat("ddMMyyyyHHmm");
Date d = s1.parse("02/11/2012 23:11");
String s3 = s2.format(d);
System.out.println(s3);
long l = Long.parseLong(s3);
System.out.println(l);

Try this,
String dateValue = "02/11/2012 23:11";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = simpleDateFormat.parse(dateValue);
simpleDateFormat = new SimpleDateFormat("ddMMyyyyHHmm");
String value = simpleDateFormat.format(date);
Long result = Long.parseLong(value);
System.out.println("Result : "+result);

Time zone is critical to parsing a string into a date-time value unless you absolutely sure all the strings represent date-times occurring in the same time zone.
Joda-Time makes this work much easier.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yyyy hh:mm" );
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = formatter.withZone( timeZone ).parseDateTime( myString );
long millisecondsSinceEpoch = dateTime.getMillis();

Related

how to change format of date from string date

I have date as a string like this
String date = "11-12-2018"
I want to change it to "2018-12-11"
with the same variable. So, I tried the code below but it doesn't give me the output I expect.
String date = "11-12-2018"
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date d = df.parse(date);
results in:
"0012-06-09"
I want
"2018-12-11"
You can do this 3 ways. First is using SimpleDateFormat and Date and second using DateTimeFormatter and LocalDate and third you can use Split.
1. Using Date and SimpleDateFormat
String date = "11-12-2018";
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date d = df.parse(date);
String finalDate = new SimpleDateFormat("yyyy-MM-dd").format(d);
System.out.println(finalDate);
Here we have our actual date String date = "11-12-2018"; we know we want to change it to 2018-12-11
So lets parse that date into a Date object using this code
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date d = df.parse(date);
Okay so now we have a date object of our actual date, Now lets format it to our new date.
String finalDate = new SimpleDateFormat("yyyy-MM-dd").format(d);
2. Using LocalDate and DateTimeFormatter
Alright here we define our date again and 2 DateTimeFormatter.
DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
The first formatter is our old date format, and the second one is the new one that we are gonna convert the old date into.
Alright lets use them now!
Now we make a new LocalDate object using our oldFormatter by parsing our dateString with the oldFormatter object
LocalDate dateTime = LocalDate.parse(date, oldFormatter);
Alright now lets format it.
String reformattedDate = dateTime.format(newFormatter);
as simple as that! Here is the full code.
String date = "11-12-2018";
DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(date, oldFormatter);
String reformattedDate = dateTime.format(newFormatter);
System.out.println(reformattedDate);
3. Using String::Split
Okay this part is pretty simple. Lets split the date using -
String[] dates = date.split("-");
We already know the order of the date lets format it using String::format
String reformattedDate = String.format("%s-%s-%s", dates[2], dates[1], dates[0]);
Here is the full code
String date = "11-12-2018";
String[] dates = date.split("-");
String reformattedDate = String.format("%s-%s-%s", dates[2], dates[1], dates[0]);
System.out.println(reformattedDate);
Try code below that will work for your case:
First parse your input format from string,
String date = "11-12-2018";
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Then convert it to desired format,
Date dateTobeParse = null;
try {
dateTobeParse = df.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
if (dateTobeParse != null) {
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
String outputDate = outFormat.format(dateTobeParse);
}
This is the common function which I use for date and time conversion
public String convertDateAndTime(String date, String oldFormat, String newFormat) {
SimpleDateFormat sdf = new SimpleDateFormat(oldFormat);
Date currentdate;
String converted = "";
try {
currentdate = sdf.parse(date);
SimpleDateFormat sdf2 = new SimpleDateFormat(newFormat);
converted = sdf2.format(currentdate);
} catch (ParseException e) {
e.printStackTrace();
}
return converted;
}
You just have to pass the date string and their old and new formats.
In your case call this function like this
String converteddate = convertDateAndTime("11-12-2018","dd-mm-yyyy","yyyy-MM-dd");
Try the code below that will work
1) Make method like below
public String changeDateFormat(String currentFormat, String requiredFormat, String dateString) {
String result = "";
SimpleDateFormat formatterOld = new SimpleDateFormat(currentFormat, Locale.getDefault());
SimpleDateFormat formatterNew = new SimpleDateFormat(requiredFormat, Locale.getDefault());
Date date = null;
try {
date = formatterOld.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
result = formatterNew.format(date);
}
return result;
}//end of changeDateFormat()
1st argument of the method is your current date format in your case it will be 'dd-MM-yyyy'
2nd argument is output or requires date format in your case it will be 'yyyy-MM-dd'
3rd argument is your date that you want to change the format
2) Run the method like below
String oldFormatDate = "11-12-2018";
String myDate = changeDateFormat("dd-MM-yyyy", "yyyy-MM-dd", oldFormatDate);
Log.d(TAG, "Old formatted Date : " + oldFormatDate);
Log.d(TAG, "New Date is : " + myDate);
3) Output:
Old formatted Date : 11-12-2018
New Date is : 2018-12-11

How to save date (dd.mm.yyyy) in java

I am getting a date in the form of dd.mm.yyyy and want to save it as a proper object. It should be comparable to another date object. How do I realize this?
Use SimpleDateFormat as this:
Date date = new SimpleDateFormat("dd/MM/yyyy").parse("12/05/2015");
Using JodaTime
String input = "03.01.2015";
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy");
DateTime dt = DateTime.parse(input, formatter);
DateTime now = new DateTime();
System.out.println(dt.compareTo(now));
Use SimleDateFormat
String string = "03.01.2015";
DateFormat format = new SimpleDateFormat("MM.dd.yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date);
Try this code
try {
SimpleDateFormat sdf= new SimpleDateFormat("dd.MM.yyyy");
Date d = sdf.parse("19.05.2090");
System.out.println(d);
} catch (ParseException ex) {
ex.printStackTrace();
}

Compare two dates with time whose Formate is yyyy-MM-dd HH:mm:ss in Android

I have to compare two dates whose format is yyyy-MM-dd HH:mm:ss. I know the way to compare date only the before or after date function.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String expiryTime = "2014-09-10 00:00:00";
But what's the best way to compare date and time with the current date and time.
Like we have two dates 2014-09-10 00:00:00 and current date with time is 2014-08-31 10:37:15. And now we have to compare it. How we can do that.
Any help is appreciated.
Convert the Date String to java.util.Date object using SimpleDateFormat and compare those date objects with Date#after or Date#before methods.
In java 8 - using new Java Time API, parse date String using DateTimeFormat and get LocalDate object and compare them.
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
final LocalDate dt1 = dtf.parseLocalDate(dateString1);
final LocalDate dt2 = dtf.parseLocalDate(dateString2);
final boolean check = dt1.isAfter(dt2);
if(check)
System.out.println(dt1 +" is after "+dt2);
else
System.out.println(dt2 +" is after "+dt1);
If I understand what you're trying to do you want to use a SimpleDateFormat (and you posted a good pattern) to parse the String(s) into Date(s) and then Date.before(Date). Putting that together into something like,
DateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String firstStr = "2014-09-10 00:00:00";
String secondStr = "2014-08-31 10:37:15";
Date first = sdf.parse(firstStr);
Date second = sdf.parse(secondStr);
boolean before = (first.before(second));
System.out.printf("%s is before %s",
before ? firstStr : secondStr,
before ? secondStr : firstStr);
Output is
2014-08-31 10:37:15 is before 2014-09-10 00:00:00
try{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
} catch (ParseException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
String str1 = "2014-09-10 00:00:00";
Date date1 = formatter.parse(str1);
String str2 = "2014-08-31 10:37:15";
Date date2 = formatter.parse(str2);
if (date1.compareTo(date2)<0)
{
System.out.println("date2 is Greater than my date1");
}

Date convert in Java

I want to compare two dates, for that i convert the string to date format.But during the conversion the date format changed to "02/01/2013" and "03/01/2014".It makes error in my logic.any one please tell me to how to compare two days in my date format.
String fdate="01/02/2012";
String tdate="01/03/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date frmdt=new Date(fdate);
String s1 = sdf.format(frmdt);
Date todt=new Date(tdate);
String s2 = sdf.format(todt);
Date frmdate = sdf.parse(s1);
Date todate = sdf.parse(s2);
if(frmdate.compareTo(todate)<=0){
//process;
}
Try this:
String fs = "01/02/2012";
String ts = "01/03/2013";
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
sdf.setLenient(false);
Date fdate = sdf.parse(fs);
Date tdate = sdf.parse(ts);
if (fdate.before(tdate) || f.date.equals(tdate)) {
//process;
}
You've got too much going on. It's much simpler.
It seems to me that you should be calling SimpleDateFormat.parse instead:
// Using the US locale will force the use of the Gregorian calendar, and
// avoid any difficulties with different date separator symbols etc.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // Avoid DST complications
sdf.setLenient(false);
Date fromDate = sdf.parse(fromDateText);
Date toDate = sdf.parse(toDateText);
// Alternatively: if (!fromDate.after(toDate))
if (fromDate.compareTo(toDate) <= 0) {
...
}
I'd actually suggest that you use Joda Time if at all possible, where you could use a LocalDate type to more accurately represent your data.
You're doing it wrong :)
String fdate="01/02/2012";
String tdate="01/03/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date frmdate = sdf.parse(fdate);
Date todate = sdf.parse(tdate);
if(frmdate.compareTo(todate)<=0){
//process;
}
You were passing to Date a not parsed date with your format. Also Date(String) is deprecated. DateFormat.parse(String) is the correct one.

Convert string to date format in android

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 ""
}
}

Categories