How can I convert a date to this particular string representation? - string-formatting

LblExpirydate.Text = dataReader(0).ToString()
Output in asp.net form : 01/05/2013 12:00:00 AM
I want to change format to (01/05/2013)
Notes : My database
Column : Expirydate
data type : Date

You can format the string using .ToString() in several different ways:
dataReader(0).ToString("dd/MM/yyyy");
dataReader(0).ToString("d");
The second option is better as it will format using the current locale. See this MSDN article for more info:
http://msdn.microsoft.com/en-gb/library/az4se3k1.aspx

DateTime thisDate1 = DateTime.Now;
Label1.Text =thisDate1.ToString("MM/dd/yyyy") ;
output:
03/30/2013
DateTime thisDate1 = DateTime.Now;
Label1.Text =thisDate1.ToString("MM-dd-yyyy") ;
output:
03-30-2013
DateTime thisDate1 = DateTime.Now;
Label1.Text =thisDate1.ToString("MM,dd,yyyy") ;
output:
03,30,2013
DateTime thisDate1 = DateTime.Now;
Label1.Text =thisDate1.ToString("MMMM,dd,yyyy") ;
output:
March,30,2013
and so on...

Related

how to update datetime colum (mssql) with formatted current datetime in querydsl

I want to update datetime column with current datetime.
but I've got an error at QAa.aaa.visitDt line.
The data type of QAa.aaa.visitDt is DateTimePath<java.time.LocalDateTime>
```
Date date = new Date();
String updDt = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
Long ret = queryFactory.update(QAa.aaa)
.set(QAa.aaa.visitCnt, QAa.aaa.visitCnt.add(1))
.set(QAa.aaa.visitDt, Expressions.dateTimePath(LocalDateTime.class, updDt))
.where(QAa.aaa.aNo.eq(aNo))
.execute();
Error Message is below.
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ~
column 90 [update ~~
set aaa.visitCnt =aaa.visitCnt + ?1, aaa.visitDt= 2022-09-12 13:24:36.330
where aaa.aNo = ?3

How to add days to date time in Salesforce Apex?

Hi I am using Salesforce Apex,
I have a date as String as below. I need to add days to it using Apex.
String dateTime = '2017-07-08T23:59:59Z';
If I add one day to it then it should be 2017-07-09T23:59:59Z as string. How will I do this?
Thanks!
Beware the DST issue! The "addDays" function is not DST-aware, so if you step over a DST transition during the addition of days (in a time zone that has DST) then the time will be messed up.
To resolve this one split the date/time into separate date and time parts first, add the days to the date part then re-combine at the end, like:
DateTime dt = ...;
Integer days = ...;
Date d = dt.date().addDays(days);
Time t = dt.time();
dt = DateTime.newInstance(d, t);
If you are working in the UK (London) time zone the following anonymous Apex illustrates the issue nicely:
DateTime dt = DateTime.newInstance(2017, 10, 28, 23, 59, 59);
System.debug('Adding days directly: ' + dt.addDays(2));
Date d = dt.date().addDays(2);
Time t = dt.time();
dt = DateTime.newInstance(d, t);
System.debug('Adding days in parts: ' + dt);
You need to convert the string to a DateTime and then add days. You can format it back after
String stringDateTime = '2017-07-08T23:59:59Z';
DateTime dt = DateTime.valueOfGmt(stringDateTime);
DateTime tomorrow = dt.addDays(1);
DateTime nextMonth = dt.addMonths(1);
DateTime anniversary = dt.addYears(1);
String formattedDateTime = dt.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');

jsp insert time in database

PreparedStatement pstmt = conn.prepareStatement(
"INSERT INTO discussion(section_id, weekday, room, mandatory, starttime,endtime)
VALUES ( ?, ?, ?, ?, ?, ?)");
pstmt.setInt(1, Integer.parseInt(request.getParameter("SECTION_ID")));
pstmt.setString(2, request.getParameter("WEEKDAY"));
pstmt.setString(3, request.getParameter("ROOM"));
pstmt.setString(4, request.getParameter("MANDATORY"));
pstmt.setString(5, request.getParameter("starttime"));
pstmt.setString(6, request.getParameter("endtime"));
right now I set the starttime and endtime in database as time without timezone type
if I use setTime to get the endtime and startime. how to modify this code
I didn't use any class here. I don't think I can use method here
the data is from user input
Suppose your dateString intered by user is in format dd-MMM-yyyy HH:mm:ss
Then you can use setDate like this
private static final String TIME_FORMAT = "HH:mm:ss";
public static final SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
pstmt.setTime(5,new Time(timeFormat.parse(request.getParameter("starttime")).getTime()));
Hope this will help
1.you should this method:
PreparedStatement pstmt;
pstmt = con.prepareStatement("INSERT INTO table_name (starttime,endtime)VALUES(?,?)");
pstmt.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime));
pstmt.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime));
pstmt.executeUpdate();
sample:
PreparedStatement pstmt;
pstmt = con.prepareStatement("INSERT INTO table_name (col_name)VALUES(?)");
pstmt.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime));
pstmt.executeUpdate();
2.Another one interesting answer:
You can use SimpleDateFormat to parse a String in the given pattern to a java.util.Date object.
Assuming that it's HH:mm, then you can do so:
String time = request.getParameter("time");
Date date = null;
try
{
date = new SimpleDateFormat("HH:mm").parse(time);
}
catch (ParseException e)
{
request.setAttribute("time_error", "Please enter time in format HH:mm");
}
Once having the java.util.Date object, you can store it in a TIME column by converting it to java.sql.Time and using PreparedStatement#setTime().
PreparedStatement pt;
pt = connection.prepareStatement("INSERT INTO tablename (columname) VALUES (?)");
pt.setTime(1, new Time(date.getTime()));
pt.executeUpdate();

select by date from appngine

First all I sorry on my english.
I development in gwt and I have appengine server.
I have question
1) how I can select row by date.
I write this
String query = "select key from " + MyClass.class.getName();
Query q = pm.newQuery(query);
String filter = "date<= 'Tue Mar 04 19:34:12 IST 2014'";
q.setFilter(filter);
int totalAgendaToNextWeekCounter += ((List<Integer>) q.execute()).size();
but is not work i get always 0.
thank you everybody
It will help to convert the date parameter from a string to a java.util.Date, and pass it as a query parameter, in something like:
Query q = pm.newQuery(query);
int totalAgendaToNextWeekCounter = 0;
try {
java.text.DateFormat dateformat = java.text.DateFormat.getDateInstance();
java.util.Date paramDate = dateformat.parse("2014-03-04T19:34:12");
String query = "select key from " + MyClass.class.getName();
q.setFilter( "date <= :paramDate" );
totalAgendaToNextWeekCounter = ((List<Integer>) q.execute(paramDate)).size();
}
catch (java.text.ParseException ex) {
java.util.logging.Logger.getLogger(logName).severe("");
}
finally {
q.closeAll();
}
This may not fit exactly in your program, but the important thing is not to pass the date parameter as a string.

sql server date in the format yyyy-MM-ddThh:mm:ssZ

I need to format a set of dates in SQL server to the following format..
yyyy-MM-ddThh:mm:ssZ
I cant seem to find how to format the date with the T and Z parts included in the string
Any ideas how to achieve this format in a SQL query?
According to the SQL Server 2005 books online page on Cast and Convert you use date format 127 - as per the example below
CONVERT(varchar(50), DateValueField, 127)
SQL Server 2000 documentation makes no reference to this format - perhaps it is only available from versions 2005 and up.
Note on the time zone added to the end (from note 7 in the docs): The optional time zone indicator, Z, is used to make it easier to map XML datetime values that have time zone information to SQL Server datetime values that have no time zone. Z is the indicator for time zone UTC-0. Other time zones are indicated with HH:MM offset in the + or - direction. For example: 2006-12-12T23:45:12-08:00.
Thanks to Martin for this note: You should be able to use STUFF to remove the miliseconds as these will be in a fixed position from the left of the string. i.e.
SELECT STUFF(CONVERT(VARCHAR(50),GETDATE(), 127) ,20,4,'')
DECLARE #SampleDate DATETIME2(3) = '2020-07-05 23:59:59';
SELECT CONVERT(VARCHAR(20), CONVERT(DATETIMEOFFSET, #SampleDate), 127);
--results: 2020-07-05T23:59:59Z
You can parse C# output in SQL using below:
SELECT CONVERT(DATETIME, CONVERT(DATETIMEOFFSET,'2017-10-27T10:44:46Z'))
Use C# to generate this using the following:
string ConnectionString = "Data Source=SERVERNAME; Initial Catalog=DATABASENAME; Persist Security Info=True; User ID=USERNAME; Password=PASSWORD";
using(SqlConnection conn = new SqlConnection(ConnectionString))
{
DateTime d = DateTime.Now;
string Query = "SELECT CONVERT(DATETIME, CONVERT(DATETIMEOFFSET,'" + d.ToString("yyyy-MM-dd") + "T" + d.ToString("HH:mm:ss") + "Z'))"
conn.Open();
using(SqlCommand cmd = new SqlCommand(Query, conn))
{
using(SqlDataReader rdr = cmd.ExecuteReader())
{
if(rdr.HasRows)
{
while(rdr.Read())
{
for(int i; i < rdr.length; i++)
{
Console.WriteLine(rdr[0].ToString());
}
}
//DataTable dt = new DataTable(); dt.Load(rdr); //Alternative method if DataTable preferred
}
}
}
}
select left(convert(varchar(30),getdate(),126)+ '.000',23)
Try this
SELECT STUFF(
CONVERT(datetime2(0), GETDATE(), 126)
AT TIME ZONE 'US Eastern Standard Time'
,11,1,'T')
on MSSQL
SELECT FORMAT( GETDATE(),'yyyy-MM-ddTHH:mm:ss.ms zzzz')

Resources