How to get formatted date into p:calendar [duplicate] - jsf

This question already has answers here:
Primefaces Calendar component & date conversions
(2 answers)
Closed 5 months ago.
I am developing a JSF and primefaces application. In my some.xhtml file where I put p: calendar tag and I want to set its default value as current date (format e.g:01-09-2014). I have written private Date startDate; in backing bean.
<p:calendar value="#{bean.startDate}">
When I don't write below code and just assign
private Date startDate = Calendar.getInstance(); it gives me default value(MON Sep 1 00:00:00 EST 2014) but not in proper format (01-09-2014) which I really want. So my question is that how to set date in custom format (01-09-2014) and assign it to Date object private Date startDate = this.defaultDate(); (see below:) to get default value in clientside
with this(01-09-2014) format.
I am using jdk 1.7.
private Date startDate = this.defaultDate();
private Date defaultDate() {
Date defaultDate = null;
try {
DateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
defaultDate = sdf.parse(sdf.format(Calendar.getInstance().getTime()));
} catch (Exception e) {
e.printStackTrace();
}
return defaultDate;
}

You are parsing the date correctly (kind of, see below) with the DateFormatter but not formatting it again for display:-
sdf.format(defaultDate);
That is to say, when you output it:-
System.out.println(sdf.format(defaultDate));
A Date object only holds an actual date, not information on how it should be formatted or which pieces of information contained in the Date to display (seconds, minutes, hours, day of week, day of month, month, year). Hence the use of DateFormatter to select only the parts you wish to display, in the order you wish to display them.
Additionally
When you are originally getting the date:-
defaultDate = sdf.parse(sdf.format(Calendar.getInstance().getTime()));
You are getting a Date object (with Calendar.getInstance().getTime()), converting it to a String using your DateFormatter (with sdf.format()) then using your DateFormatter to convert it back to a Date (with sdf.parse()) when you could just do:-
Date defaultDate = Calendar.getInstance().getTime();

you can use
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String displayDate = dateFormat.format(new Date());
this will give you formatted date in the format dd-MM-yyyy as string

Related

Moment.js - formatting an existing time?

I am using moment.js to work with dates and times in node.js. So far I've been able to do everything I need with it, but I am having problems formatting a time.
Here's the scenario:
User enters data (an integer), which is logged in a database, along with date (in the format YYYY-MM-DD) and time (in the format HH:MM:SS).
Next time the user goes to enter data, the previous value is read in and compared (higher, lower or equal to) the new value. However I also want to display a message such as "The last time you submitted your data was at TIME on DATE". In this case, I'd like time to be displayed in a different format (e.g. "h:mm a" i.e. "12:34 pm").
Can I use moment to format an existing date, or can moment only return current date/time? In my code I have the following function:
function userFormattedTime(time)
{
let uTime = moment(time).format('h:mm a');
return uTime
}
However when I call this function and pass it the time (taken from the database), I get "Invalid Time". What am I doing wrong?
You would parse the string from a string back to a moment object, then you can use moment to reformat the date into any other format.
I guess what you are doing wrong is not telling moment what you're sending it back, i.e. it doesn't understand the formatted string you're supplying.
Notice the format values HH:mm:ss which vary in case. The case is important and should be set to match your requirements. https://momentjs.com/docs/#/parsing/
// Original date time string
var rawDateTime = "02-02-2018 10:20:30";
// convert string to a moment object
var originalDate = moment(rawDateTime, "MM-DD-YYYY HH:mm:ss");
// Format a new string from the moment object
var newFormattedString = originalDate.format('h:mm a');
In order to calculate the difference of moment objects you can use the diff function. https://momentjs.com/docs/#/displaying/difference/
// Two different dates
var dateOne = moment("02-02-2018 10:20:30", "MM-DD-YYYY HH:mm:ss");
var dateTwo = moment("04-04-2018 10:20:30", "MM-DD-YYYY HH:mm:ss");
// Get the difference of the two dates
var diff = dateOne.diff(dateTwo);

split date month and year in different fields

I have a date stored in my database in this format:
2013-01-08T17:16:36.000Z
I have searched for it a lot but it shows how to get this date format but what I am looking for is want to separate this like:
a=yyyy,b=dd and c=mm
And the rest is not required because I want to show date, month and year all this three in different fields.
I want to store the date in one variable, month in another variable and year in another one.
I tried this https://jsfiddle.net/ccywo7a9/ and actually works but i want this using split in node.js
This works
var Date='2013-01-08T17:16:36.000Z';
var b=Date.slice(0,10);
var c=b.split('-');
var e=c[Symbol.iterator]();
console.log(e.next().value);
console.log(e.next().value);
console.log(e.next().value);
and gives the value in three different variables.
Output:
2013
01
08
Try this method.. it's convert Mongo DB date and Time format...
String dateParts[] = "2013-01-08T17:16:36.000Z".split("T");
String split_date = dateParts[0];
String sp_time = dateParts[1];
System.out.println("sp_date----"+split_date);
String dateParts2[] = sp_time.split("Z");
String split_time = dateParts2[0];
System.out.println("sp_time----"+split_time);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss.SSS");
SimpleDateFormat cnv = new SimpleDateFormat("MMM dd hh:mm a");
Date modified_date = null;
try {
modified_date = format.parse(split_date+split_time);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("DATE----------------------"+cnv.format(modified_date));
Result :Jun 06 10:58 AM

How to remove time from date and time

In DOB i am getting date and time but i need only date
foreach (DataRow row in ProfileDt.Rows)
{
UserProfileData.FirstName = row["FirstName"].ToString();
UserProfileData.LastName = row["LastName"].ToString();
UserProfileData.Email = row["Email"].ToString();
UserProfileData.Address = row["HouseNo"].ToString();
UserProfileData.City = row["CityName"].ToString();
UserProfileData.date = row["DOB"].ToString();
}
If your database is giving you a string then you'll need to parse it to a date then back to a string with the desired date format.
string dateFormat = "MM/DD/YYYY HH:mm:ss" // REPLACE WITH THE CORRECT FORMAT
UserProfileData.date = DateTime.ParseExact(row["DOB"].ToString(), dateFormat ,
System.Globalization.CultureInfo.InvariantCulture).ToString("MM/DD/YYYY");
If your database is giving you a datetime directly (which is the better solution) then it becomes even easier.
UserProfileData.date = ((DateTime)row["DOB"]).ToString("MM/DD/YYYY");
Convert your string to DateTime type and use Date property, something like yourDate.Date
You can use DateTime.Parse or DateTime.ParseExact for parsing string to DateTime
It also make sense to return DateTime type directly from database so you do not need any conversions...

Converting String to datefield / Java Microedition

Using J2ME, netbeans 7.2, Developing a mobile app..
I have converted the Datefield value to a String and Now want to put it back to a Datefield. To do this I need to convert the String back to Datefield, I am using the following code but its not happening.
long myFileTime = dateField.getDate().getTime(); // getting current/set date from the datefield into long
String date = String.valueOf(myFileTime); // converting it to a String to put it back into a different datefield
Date updatedate= stringToDate(date); // passing the string 'date' to the Method stringToDate() to convert it back to date.
dateField1.setDate(updatedate); // updating the date into the new datefield1
public Date stringToDate(String s)
{
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(s.substring(0, 2)));
c.set(Calendar.MONTH, Integer.parseInt(s.substring(3, 5)) - 1);
c.set(Calendar.YEAR, Integer.parseInt(s.substring(6, 10)));
return c.getTime();
}
Since you have mentioned that you have the long myFileTime around, you should be able to use:
Date updatedate=new Date(myFileTime);
To convert back to your date. If only your String is available, you should modify your function to this:
public Date stringToDate(String s){
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(s.substring(0, 2)));
c.set(Calendar.MONTH, Integer.parseInt(s.substring(2, 4))-1 );
c.set(Calendar.YEAR, Integer.parseInt(s.substring(4, 8)));
return c.getTime();
}
Note the changed indexes.
In Java SE, you should be able to use the following line, instead of setting each fields separately:
c.setTimeInMillis(Long.parseLong(s));
Since in s you have the dateField.getDate().getTime() that is equal to myFileTime, the number of seconds starting with January 1, 1970, based on your provided code.
Your stringToDate should work only if your string will have the following format: ddMMyyyy. Also note that in this case you should use a SimpleDateFormat to parse, something like:
Date updatedate = new java.text.SimpleDateFormat("ddMMyyyy HH:mm:ss").parse(date);

convert strings to datetime

I have asp.net application and am using Entity Framework to connect it with the database. in this application, I have a textbox to get the date(am using calender css style here), and its in the string type.
I have a column in my database and its in Date Time format, I need to compare the textbox value with the date column in my database, for this I just used the code as
public StudentAttendances(string date)
{
if (date != "")
{
DateTime date1 = Convert.ToDateTime(date);
foreach (DataAccess.StudentAttendance studentAttendance in buDataEntities.StudentAttendances.Where(s => s.Date == date1))
{
this.Add(new StudentAttendance(studentAttendance.StudentId));
}
}
}
for example if I select a date in my textbox(the format is 04/05/2012) and when I compare this with the database its not showing any data, but actually some datas are there for this date.
Your code is comparing both day and time (hours, minutes etc will have to match). Try comparing just the day part like this:
buDataEntities.StudentAttendances.Where(s => s.Date.Subtract(date1).Days == 0)
I also think that you should specify what format the input date from the users is in.
04/05/2012 may mean both 4th April or 5th of May depending on your computers regional setting.
Here is an example (below) for converting a date string in American format to DateTime object:
DateTime date1 = DateTime.Parse(date, new CultureInfo("en-US"));
Hope that helps!
your ask is very limited, but try to see this
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
Please check whether the following works for you:
public StudentAttendances(string date)
{
if (date != "")
{
// please see the change from your given code
DateTime date1 = DateTime.ParseExact(date, "MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
foreach (DataAccess.StudentAttendance studentAttendance in buDataEntities.StudentAttendances.Where(s => s.Date == date1))
{
this.Add(new StudentAttendance(studentAttendance.StudentId));
}
}
}

Resources