convert string to date and time as am/pm format [duplicate] - java

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 8 years ago.
string : 2014-04-25 17:03:13
using SimpleDateFormat is enough to format?
or
otherwise i will shift to any new API?
Date date = new Date(string);
DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd");
out.println( dateFormat.format (date));
My expected result is (India zone):
Date : 25-04-2014
Time : 05:03 PM

Remembering that Date objects have no inherent format, you need two DateFormat objects to produce the result you seek - one to parse and another to format:
String input = "2014-04-25 17:03:13";
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat outputFormat = new SimpleDateFormat("'Date : 'dd-MM-yyyy\n'Time : 'KK:mm a");
System.out.println(outputFormat.format(inputFormat.parse(input)));
Output:
Date : 25-04-2014
Time : 05:03 PM
Note the use of quoted sequences in the format, such a "'Date : '", which is treated as a literal within the format pattern.

I custom onTimeSet() function . Send the hour and minutes to it. It will return the time with format am and pm
public static String onTimeSet( int hour, int minute) {
Calendar mCalen = Calendar.getInstance();;
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format_local = mCalen.get(Calendar.HOUR);
int hourOfDay_local = mCalen.get(Calendar.HOUR_OF_DAY);
int minute_local = mCalen.get(Calendar.MINUTE);
int ampm = mCalen.get(Calendar.AM_PM);
String minute1;
if(minute_local<10){
minute1="0"+minute_local;
}
else
minute1=""+minute_local;
String ampmStr = (ampm == 0) ? "AM" : "PM";
// Set the Time String in Button
if(hour12format_local==0)
hour12format_local=12;
String selecteTime=hour12format_local+":"+ minute1+" "+ampmStr;
retrun selecteTime;
}

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
more patterns you can find here

Try given below sample code:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
//Output: 2013-05-20 10:16:44
For more functionalities on Data and Time try Joda-Time API .

Related

How to count down 6 month in android? [duplicate]

This question already has answers here:
android java parse date from string
(3 answers)
Closed 5 years ago.
I have a date string in this format '20161201'.
How to make this a datetime string to be july 2016?
I want to show 6 months before that datetime string.
Is it possible?
Also how do I convert just '20161201' to Dec 2016?
you change the format using the following code,
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
SimpleDateFormat expectedSDF = new SimpleDateFormat("MMMM yyyy", Locale.getDefault());
Date date = simpleDateFormat.parse(dateString);
String newFormatString = expectedSDF.format(date);
And for the countdown, use CountDownTimer
https://developer.android.com/reference/android/os/CountDownTimer.html
For convert '20161201' to 'Dec 2016':
//Convert string to date
String dateString = "20161201";
SimpleDateFormat parseDateFormat = new SimpleDateFormat("yyyyMMdd");
Date convertedDate = new Date();
try {
convertedDate = parseDateFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
//Convert date to string
SimpleDateFormat outputDateFormat = new SimpleDateFormat("MMM yyyy");
String result = outputDateFormat.format(convertedDate);
//Print the result
System.out.println(result);
In '6 months' to millisecond is 15778476000. You can get the date after 6 months in millisecond by using
long resultdate = convertedDate.getTime() - 15778476000L;
and then
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(resultdate);
String result = outputDateFormat.format(calendar.getTime());
to get the result
https://developer.android.com/reference/java/text/SimpleDateFormat.html
https://developer.android.com/reference/java/util/Date.html
https://developer.android.com/reference/java/util/Calendar.html#setTimeInMillis(long)
how to make this datetime string to be july 2016
I want to show 6 months before that datetime string
July is 5 months...
Here's the 6 month answer
java.util.Calendar c = java.util.Calendar.getInstance();
c.setTime(new SimpleDateFormat("yyyyMMdd").parse("20161201"));
c.set(Calendar.MONTH, c.get(Calendar.MONTH)-6);
String output = new SimpleDateFormat("MMMM yyyy").format(c.getTime()));
// June 2016

How can I extract date from since time component [duplicate]

This question already has answers here:
How to convert currentTimeMillis to a date in Java?
(13 answers)
Closed 7 years ago.
I have to extract date in the format MM-dd-yyyy in java from the since time value. Since time is the time at which the doucment is created. For example, if since time is 1452413972759, date would be "Sun, 10 Jan 2016 08:19:32 GMT" (Calculated from http://www.epochconverter.com/) . From this, I could get date in desired format but I am unable to code for the first step i.e., converting since time to date. Can someone help me?
I tried
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
java.util.Date date = df.parse("1452320105343");
String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + sdf.format(date));
But it gives parse exception.
Your code can't work because you're trying to parse a number of milliseconds as if it was a MM/dd/yyyy formatted date.
I would have expected the following code to work, where S represents milliseconds :
DateFormat df = new SimpleDateFormat("S");
java.util.Date date = df.parse("1452413972759");
String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + sdf.format(date));
However it doesn't for some reason, displaying a date in the 1970 year.
Instead, the following code that parses seconds rather than milliseconds works for your needs :
DateFormat df = new SimpleDateFormat("s");
java.util.Date date = df.parse("1452413972"); // just remove the last 3 digits, or divide by 1000
String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + sdf.format(date));
Or just follow the link from #mohammedkhan and use Date constructor rather than parsing a string :
java.util.Date date = new Date(1452413972759l);
String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + sdf.format(date));

I want my string to converted to a day [duplicate]

This question already has answers here:
How to determine day of week by passing specific date?
(28 answers)
Closed 7 years ago.
I have this string
String s = "29/04/2015"
And I want it to produce the name of that day in my language, which is Norwegian.
For example:
29/04/2015 is "Onsdag"
30/04/2015 is "Torsdag"
How can I do this?
String dateString = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(dateString);
SimpleDateFormat formatter = new SimpleDateFormat("E", Locale.no_NO);
String day = formatter.format(date);
Now day will have the day in given locale. Update
You need to configure an instance of DateFormat, with your locale, (take a look at https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html).
then parse the Date and get the day, as Dilip already suggests.
You can use date parsing combined with Locale settings to get the desired output. For e.g. refer following code.
String dateStr = "29/04/2015";
SimpleDateFormat dtf = new SimpleDateFormat("dd/MM/yyyy");
Date dt = dtf.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
String m = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG_FORMAT, new Locale("no", "NO"));
System.out.println(m);
For more information about locale, visit Oracle Java Documentation.
First you will need to parse the String to a Date. Then use a Calendar to get the day of the week. You can use an array to convert it to the appropriate string.
// Array of Days
final String[] DAYS = {
"søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"
};
// Parse the date
final String source = "27/04/2015";
final DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
try {
date = format.parse(source);
} catch (final ParseException e) {
e.printStackTrace();
}
// Convert to calendar
final Calendar c = Calendar.getInstance();
c.setTime(date);
final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
// Get the day's name
System.out.println("Day of Week: " + dayOfWeek);
System.out.println("Day = " + DAYS[dayOfWeek - 1]);
You need to parse your text with date to Date instance and then format it back to text. You can do it with SimpleDateFormat class which supports many patterns of dates like
dd/MM/yyyy for your original date,
and EEEE for full name of day in month.
While formatting you will also need to specify locale you want to use. To create Norway specific locale you can use for instance
Locale nor = Locale.forLanguageTag("no-NO");
So your code can look more or less like:
String text = "29/04/2015";
Locale nor = Locale.forLanguageTag("no-NO");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", nor);
SimpleDateFormat dayOfWeek = new SimpleDateFormat("EEEE", nor);
Date date = sdf.parse(text);
System.out.println(dayOfWeek.format(date));
Output: onsdag.
final int SUNDAY = 1;
final int ONSDAG = 2;
final int TORSDAG = 3;
....
....
String s = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(s);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_WEEK);
String dayString;
switch (day) {
case(ONSDAG):
dayString = "ONSDAG";
break;
....
}
EDIT: I just tested this and it actually starts from Sunday, and returns the value of 1 for sunday, I've changed the constant values to reflect this.
First you'll need a Calendar object.
Calendar cal = Calendar.getInstance();
String s = "29/04/2015"
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
cal.setTime(format.parse(s));
From the Calendar you can get the day of the week.
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
dayOfWeek will be 1-7 with Sunday (in english) being 1
You can use an HashMap map where the first parametri is the date "29/4/2015" while the second is the meaning. You can use your string to get the meaning map.get (yourString).

How to remove millisec from date and time [duplicate]

This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 8 years ago.
I have a object that giving date and time in this format "2014-06-11 16:32:36.828".
I want to remove millisec .828.
In my db that object is in time stamp format but whenever i am showing i am converting it to tostring().
so how to remove millisec please help me
The following code convert "2014-06-11 16:32:36.828" into "2014-06-11 16:32:36"
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2014-06-11 16:32:36.828"));
Explanation:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2014-06-11 16:32:36.828") parse the input string into
Wed Jun 11 16:32:36 IST 2014
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) format the input date into specified structure.
I would use DateUtils.truncate(date, Calendar.SECOND)
Date d = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(yourString);
Calendar c = Calendar.getInstance();
c.setTime(d);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
I remember there is a way to directly read Date off your timestamp field but I don't do that in my everyday coding. So I'd left for others to post so. Nevertheless, you can use the same above code to translate your date from that timestamp into a date without MILLISECOND.
If you receive it as a Timestamp, you should use the appropriate formatter when converting it to a string:
String s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
Note: this will use the default time zone of the local computer.
Extract epoch millis from the original Date object and do integer division by 1000 followed by multiplication by 1000. Create Date object with the time zone of the original object and the millis calculated the above suggested way.
You can get the system time as follows without milliseconds
import java.text.SimpleDateFormat;
import java.util.Calendar;
And the code
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter= new SimpleDateFormat("dd-MM-YYYY-hh:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
System.out.println(dateNow);
if you want to mantain the format try something like that:
public static String getFechaTimestampToString (Timestamp timestamp) {
String date = "";
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(timestamp.getTime()));
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DAY_OF_MONTH);
String monthstr = "";
String daystr = "";
if(month<10)
monthstr = "0"+month;
else
monthstr = ""+month;
if(day<10)
daystr = "0"+day;
else
daystr = ""+day;
date = year + "-" + monthstr + "-" + daystr ;
return date;
}
To reverse data to database:
public static Timestamp getFechaStringToTimestamp (String strDate) {
Timestamp timestamp = null;
strDate = strDate + " 00:00:00";
timestamp = Timestamp.valueOf(strDate);
return timestamp;
}

Convert String [] to timestamp [duplicate]

This question already has answers here:
Java converting a Date to a different format
(2 answers)
Closed 8 years ago.
how to convert string [] temp to Timestamp:
String[] temp = line.split(",");
for (int i = 1; i < temp.length; i++) {
objekt.setTimestamp(timestamp);}
if i use
Timestamp ts= Timestamp.valueOf(temp[0]);
objekt.setTimestamp(ts);}
i get this exceptionTimestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
if i use this
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
java.util.Date parsedDate = dateFormat.parse(temp[0]);
java.sql.Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
i get
" java.text.ParseException: Unparseable date: "06/11/2013 22:00"
thank you everyone for suggestions, i can read the timestamp but i must to read this format month-day-year: 06/18/2013 21:00:00, and with SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm"); i get 2013-06-18 18:00:00, if i change MM or dd or yyyy hier "MM/dd/yyyy HH:mm" i can't even get the month first then date and year
Your date format must actually match the text being provided. '/' and '-' do not match.
For the string you have provided, it appear the format might be "MM/dd/yyyy HH:mm".
It could also be "dd/MM/yyyy HH:mm", as it is not clear whether that date is June 11 or November 6.
Use the below code:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
Assuming that 06 in the string Unparseable date: "06/11/2013 22:00" correponds to month
On your 2nd code block where you got java.text.ParseException: Unparseable date: "06/11/2013 22:00, your SimpleDateFormat pattern is wrong as your String is "06/11/2013 22:00", So you have to use pattern :
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
For more details, see java.text.SimpleDateFormat
You can do something like this :
Timestamp ts= null;
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String[] temp = {..,..}; // it's string time array
for (int i = 1; i < temp.length; i++) {
Date convertedDate = dateFormat.parse(temp[i]);
ts = new Timestamp(convertedDate.getTime());
System.out.println(ts);
}

Categories

Resources