I am trying to convert the date and time to milliseconds but it is always giving me wrong answer please tell me how to convert this type of format date and time "5/4/2014 4:39:52 PM" in millisecond
"5/4/2014 4:39:52 PM"
I am trying to wake alarm at particular date time and according to the am and pm
thanks
You should use SimpleDateformat .
String dateString = "5/4/2014 4:39:52 PM";
SimpleDateFormat format =
new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Date date = format.parse(dateString);
long millisecond = date.getTime();
This class is used to parse strings into dates in java.
Try following code
String dateString = "05/04/2014 4:39:52 PM";
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
Date mDate = new Date();
try {
mDate = dateFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("TimeMilis : " +mDate.getTime());
Avoid using the notoriously troublesome java.util.Date and .Calendar classes.
Here is some example code using Joda-Time 2.3.
String input = "5/4/2014 4:39:52 PM";
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ); // Or, DateTimeZone.UTC
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yyyy hh:mm:ss a" );
DateTime dateTime = formatter.withZone( timeZone ).parseDateTime( input );
long millis = dateTime.getMillis();
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "millis: " + millis );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run…
input: 5/4/2014 4:39:52 PM
dateTime: 2014-04-05T16:39:52.000+02:00
millis: 1396708792000
dateTimeUtc: 2014-04-05T14:39:52.000Z
For getting AM and PM you can try below code,
private void updateTime(int hours, int mins) {
String timeSet = "";
if (hours > 12) {
hours -= 12;
timeSet = "PM";
} else if (hours == 0) {
hours += 12;
timeSet = "AM";
} else if (hours == 12)
timeSet = "PM";
else
timeSet = "AM";
String minutes = "";
if (mins < 10)
minutes = "0" + mins;
else
minutes = String.valueOf(mins);
aTime = new StringBuilder().append(hours).append(':').append(minutes)
.append(" ").append(timeSet).toString();
}
just modify a bit code and it's variable name as per your requirement.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.