Is there any method in MySql which can return the name of days between two dates. For example 06/11/207 is start date and 12/11/2017 is end date then I need to get the output as:
monday,tuesday,wednesday,thursday,friday,saturday,sunday
you can try this :
you can take F_TABLE_NUMBER_RANGE function from this link:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47685
declare #start_date datetime
declare #end_date datetime
declare #days int
select #start_date = '06/11/2017'
select #end_date = '12/11/2017'
select #days = datediff(dd,#start_date,#end_date) +1
select
[Date] = dateadd(dd,number-1,#start_date),
[Day of Week] = datename(weekday,dateadd(dd,number-1,#start_date))
from
dbo.F_TABLE_NUMBER_RANGE( 1, #days )
order by
number
This I have tried and working for me cheers !
tl;dr
Use Java. Auto-localize.
myResultSet.getObject( … , LocalDate.class ) // Retrieve a `LocalDate` object from your database.
.getDayOfWeek() // Fetch the `DayOfWeek` object appropriate for this date. Ex: DayOfWeek.MONDAY
.getDisplayName( // Generate a String of the name of day-of-week.
TextStyle.FULL , // How long or abbreviated?
Locale.US // Or Locale.CANADA_FRENCH, etc.
)
Monday
Details
Generally best to do such transformations within your app rather than SQL, IMHO.
Java has an industry-leading date-time framework now in Java 8 and later, the java.time classes.
The LocalDate class represents a date-only value without time-of-day and without time zone.
With JDBC 4.2 and later, you can directly exchange java.time objects with your database.
LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ; // Retrieval.
myPreparedStatement.setObject( … , localDate ) ; // Insert/Update.
The DayOfWeek enum offers seven existing objects, one for each day of the week. Use the getDisplayName method to generate an automatically localized name for the day-of-week.
DayOfWeek dow = localDate.getDayOfWeek() ;
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
lundi
Or, US English:
DayOfWeek dow = localDate.getDayOfWeek() ;
String output = dow.getDisplayName( TextStyle.FULL , Locale.US ) ;
Monday
Compare LocalDate objects with isBefore and isAfter and other methods. Loop each date incrementally by calling LocalDate::plusDays.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Related
I want to create a java.sql.Date object of the format "YYYY". It should have only the year. I researched a lot but couldn't find a way to do it.
tl;dr
Never use terrible java.sql.Date class, badly designed with multiple flaws.
Use either java.time.Year object, or an integer.
myPreparedStatement.setObject( … , Year.of( 2018 ) ) ;
…or, while using Year in other parts of your code:
myPreparedStatement.setInt( … , Year.of( 2018 ).getValue() ) ;
java.time
The modern solution uses the java.time classes that years ago supplanted the terrible old date-time classes of SimpleDateFormat, java.util.Date, java.sql.Date, and so on.
The Year class neatly represents a year value. Using this class in your code gives you type-safety and makes your code more self-documenting.
Parsing a string input.
Year y = Year.parse( "2018" ) ;
Parsing an integer input.
Year y = Year.of( 2018 ) ; // Integer literal.
JDBC
As of JDBC 4.2 we can directly exchange java.time types.
Exchange Year object
I do not know if this includes the Year class and YEAR data type in MySQL. But give it a shot. If not, make a feature request to your JDBC driver vendor to extend support. Seems like a justifiable expectation given the fact that MySQL has an explicit YEAR type.
myPreparedStatement.setObject( … , y ) ;
Retrieval.
Year y = myResultSet.getObject( … , Year.class ) ;
Exchange integer
If your JDBC driver cannot use java.time.Year directly, use integer.
myPreparedStatement.setInt( … , y.getValue() ) ; // Pass year as an integer number.
Retrieval.
Year y = Year.of( myResultSet.getInt( … ) ) ; // Retrieve integer, convert to `Year` object.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
You need to create a java.util.Date and then convert this to a java.sql.Date using the constructor that takes in a long.
Example:
String year = "2018";
DateFormat format = new SimpleDateFormat("yyyy");
java.util.Date utilDate = format.parse(year);
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
However, it's not "only a year". Dates in Java always have a time component, so this isn't possible - it will be "1 Jan 2018 00:00:00 GMT" in my example. Is this close enough to what you want, or could you refine your question?
In addition, a java.sql.Date extends java.util.Date, so ideally you'd use the former wherever possible to satisfy the Liskov substitution principle.
I have this piece of code
while(activecheck.next()){
Date status;
String vincheck;
Date curr = new Date();
int datecheck;
status = activecheck.getDate(8);
vincheck = activecheck.getString(2);
String update = "UPDATE Auctions SET status = '"+inactive+"' WHERE vin = '"+vincheck+"'";
datecheck = status.compareTo(curr);
if(datecheck < 0){
stmt6.executeUpdate(update);
}
}
Which iterates through a mysql table checking for inactive bids. I am trying to check whether the date and time listed in the sql row has been passed by the current time. However, whenever I do this, it seems to only be comparing the dates, and not the times. What could be the cause of this?
This is the format I am using : yyyy-MM-dd HH:mm:ss`
You should use type which is called Timestamp instead of the date. This way you will cover the date and the current time
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
tl;dr
if(
myResultSet.getObject( … , Instant.class ) // Retrieve `Instant` (a moment in UTC) from database using JDBC 4.2 or later.
.isBefore( Instant.now() ) // Comparing to the current moment captured in UTC.
)
{
…
}
java.util.Date versus java.sql.Date
You may be confusing this pair of unfortunately mis-named classes. The first is a date-with-time type, in UTC. The second is a date-only type. Actually the second pretends to be a date-only type but actually has a time-of-day set to 00:00:00. Even worse, the second inherits from the first, but the documentation instructs us to ignore that fact.
Confusing? Yes. These awful classes are very poorly designed. Avoid them.
java.time
You are using terribly troublesome old date-time classes that were supplanted years ago by the java.time classes.
Instant
The java.util.Date class is replaced by java.time.Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
LocalDate
The java.sql.Date class is replaced by java.time.LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.
JDBC 4.2
As of JDBC 4.2 and later, you can directly exchange java.time classes with your database. No need to ever use java.sql or java.util date-time types again.
Tip: Make a habit of always using a PreparedStatement to avoid SQL Injection risk. Not really any more work once you get used to it.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
myPreparedStatement.setObject( … , instant ) ;
And retrieval.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
Smart objects, not dumb strings
This is the format I am using : yyyy-MM-dd HH:mm:ss`
Date-time values stored in a database do not have a “format”. Those values are stored by some internally-defined mechanism that does not concern us. They are not strings (not in any serious database, that is).
Your database, and your Java date-time objects, can parse a string representing a date-time value to create that value. And they can generate a string to represent that value. But the string and the date-time value are distinct and separate, and should not be conflated.
Use java.time objects to exchange date-time values with your database, not mere strings, just as you would for numbers and other data types your database comprehends. Use strings only for communicating textual values.
Compare
To compare your retrieved values against the current moment, use the isBefore, isAfter, and equals methods of Instant class.
Instant now = Instant.now() ;
…
Instant instant = myResultSet.getObject( … , Instant.class ) ;
boolean isPast = instant.isBefore( now ) ;
if ( isPast ) {
…
}
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I am pulling data out of an Excel sheet, to load into Hubspot, using Java.
Here is how the data looks:
this date 2018-12-31 becomes Dec 31, 2017 once it's in side Hubspot.
This is wrong!
Here is my code:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date dt = null;
try {
dt = df.parse(member.getUsageEndDate());
} catch (java.text.ParseException e3) {
//dt = null;
e3.printStackTrace();
}
Long l = dt.getTime();
If I open the data in Notepad, it looks like this: 31-May-2018
How can I get this converted properly?
tl;dr
OffsetDateTime.of(
LocalDate.parse( "2018-12-31" ) ,
LocalTime.MIN ,
ZoneOffset.UTC
)
.toInstant()
.toEpochMilli()
1546214400000
Details
Avoid legacy date-time classes
You are using troublesome old date-time classes long ago made legacy by the arrival of the java.time classes built into Java 8 and later.
ISO 8601
Your input string happens to comply with the ISO 8601 standard formats. These formats are used by default in java.time when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2018-12-31" ) ;
First moment of the day
Apparently you need the first moment of the day in UTC for that date. Use OffsetDateTime with constant ZoneOffset.UTC.
OffsetDateTime odt = OffsetDateTime.of( ld , LocalTime.MIN , ZoneOffset.UTC ) ;
Dump to console.
System.out.println( "odt.toString(): " + odt );
See this code run live at IdeOne.com.
odt.toString(): 2018-12-31T00:00Z
Count-from-epoch
You appear to want the count of milliseconds since the epoch reference date of first moment of 1970 in UTC, 1970-01-01T00:00Z. Extract an Instant object, the basic building-block class in java.time, and call its handy Instant::toEpochMilli method.
long millisecondsSinceEpoch = odt.toInstant().toEpochMilli() ;
See this code run live at IdeOne.com.
1546214400000
Going the other direction.
Instant instant = Instant.ofEpochMilli( 1_546_214_400_000L ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I have created new SimpleDateFormat object which parses the given string as date object. The date format is as below:
SimpleDateFormat simpledateFormat = new SimpleDateFormat("dd-MM-yyyy");
And I am setting this date to calendar instance as below:
Date date = sampledateFormat.parse("01-08-2013");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Now I am getting the day of the day of the week from this calendar. It is giving wrong value.
System.out.println(calendar.DAY_OF_WEEK);
The output it is giving is 7 i.e. Saturday but the expected value is 5 i.e. Thursday. Whats the problem?
You should print
calendar.get(Calendar.DAY_OF_WEEK);
The Calendar class has DAY_OF_WEEK as integer constant (with value 7) which should be used in conjunction with the Calendar.get(int) method. DAY_OF_WEEK is a calendar field, and all these constant fields are used to get() different values from the calendar instance. Their value is irrelevant.
tl;dr
LocalDate.parse( // Parse the input string by specified formatting pattern to get a date-only `LocalDate` object.
"01-08-2013" ,
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
.getDayOfWeek() // Get a `DayOfWeek` enum object. This is *not* a mere String.
.getValue() // Ask the `DayOfWeek` object for its number, 1-7 for Monday-Sunday per ISO 8601 standard.
4
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes such as SimpleDateFormat and Date and Calendar.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Define a formatting pattern to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
Parse the input string.
LocalDate ld = LocalDate.parse( "01-08-2013" , f ) ;
ld.toString(): 2013-08-01
Interrogate for the day-of-week. Get a DayOfWeek enum object, one of seven pre-defined objects, for Monday-Sunday.
DayOfWeek dow = ld.getDayOfWeek() ;
dow.toString(): THURSDAY
You can ask that DayOfWeek object for a localized name and for a number 1-7 for Monday-Sunday per the ISO 8601 standard.
int dowNumber = dow.getValue() ;
4
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; // Or Locale.US, Locale.ITALY, etc.
jeudi
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I'm trying to assign a XMLGregorianCalendar date to a java.sql.Timestamp var, like this...
var1.setTimeStamp(Timestamp.valueOf(var2.getXMLGregorianCalendar().toString()))
But apparently, this is not working, and throws an exception...
java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
And I've tried this, as well:
var1.setTimeStamp((Timestamp) var2.getXMLGregorianCalendar().getTime())
but...
java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Timestamp
Any ideas..? Thanks!
I've found the answer:
Timestamp timestamp = new Timestamp(var2.getXMLGregorianCalendar().toGregorianCalendar().getTimeInMillis());
var1.setTimeStamp(timestamp);
tl;dr
Try to avoid legacy date-time classes. But if handed a javax.xml.datatype.XMLGregorianCalendar, convert to modern java.time.Instant class. No need to ever use java.sql.Timestamp.
myPreparedStatement.setObject(
… ,
myXMLGregorianCalendar // If forced to work with a `javax.xml.datatype.XMLGregorianCalendar` object rather than a modern java.time class…
.toGregorianCalendar() // …convert to a `java.util.GregorianCalendar`, and then…
.toZonedDateTime() // …convert to modern `java.time.ZonedDateTime` class.
.toInstant() // Adjust to UTC by extracting an `Instant` object.
)
Retrieving from a database, as of JDBC 4.2 and later.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
java.time
FYI, the terribly troublesome old date-time classes have been supplanted by the java.time classes.
javax.xml.datatype.XMLGregorianCalendar is replaced by java.time.ZonedDateTime.
java.util.GregorianCalendar is replaced by java.time.ZonedDateTime. Note new conversions methods added to the old class.
java.sql.Timestamp is replaced by java.time.Instant, both representing a moment in UTC with a resolution of nanoseconds.
Avoid using XMLGregorianCalendar. But if you must interface with old code not yet updated for java.time types, convert. As an intermediate step, convert to GregorianCalendar as seen in the code of your Question.
java.util.GregorianCalendar gc = myXMLGregorianCalendar.toGregorianCalendar() ;
Now use the new convenient conversion method added to the old GregorianCalendar class, to get a modern java.time.ZonedDateTime object.
ZonedDateTime zdt = gc.toZonedDateTime() ; // Convert from legacy class to modern class.
Adjust from that particular time zone to UTC. Extract an Instant object which is a moment always in UTC, by definition.
Instant instant = zdt.toInstant() ; // Adjust from some time zone to UTC.
As of JDBC 4.2, we can directly exchange java.time objects with the database. So no need to ever touch java.sql.Timestamp again.
myPreparedStatement.setObject( … , instant ) ;
Retrieval:
Instant instant = myResultSet.getObject( … , Instant.class ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.