How can I get the first day of the week of any given year (day being 1 to 7, or weekday name)?
I tried to figure it out in JavaScript, but I accept any other language.
I need to select a year to later build the full calendar (I thought using HTML tables and JavaScript), and for that I need to know at least the first day of the selected year.
I haven't found a solution or a question specifically dealing with finding the first day of any given year such that you only need to pass 1995, 2007, 1891. So if it's a repeated question please point the solution.
Do you have at least an online chart or DHTML site where I can see any full calendar for any year visually in that way?
In Javascript you can use this:
getWeekDay = function (year) {
var d = new Date();
d.setFullYear(year,0,1);
return d.getDay()+1;
};
document.write(getWeekDay(2011));
Result is 1..7, as requested.
At this Wikipedia article, look for Sakamoto's algorithm.
Pretty easy with C# and .NET:
using System;
public class SomeClass
{
public static void Main()
{
DateTime dt = new DateTime(2000,1,1);
Console.WriteLine(dt.DayOfWeek);
dt = new DateTime(2010,1,1);
Console.WriteLine(dt.DayOfWeek);
}
}
Output:
Saturday
Friday
The Java version:
import java.util.Date;
import java.util.GregorianCalendar;
public class test3
{
public static void main (String[] args)
{
GregorianCalendar c = new GregorianCalendar(2000,1,1);
Date d = c.getTime();
System.out.println(d.getDay());
c = new GregorianCalendar(2010,1,1);
d = c.getTime();
System.out.println(d.getDay());
}
}
Output:
2
1
With .NET's BCL:
return new DateTime(year, 1, 1).DayOfWeek; // DayOfWeek enum value
In Noda Time:
return new LocalDate(year, 1, 1).IsoDayOfWeek; // IsoDayOfWeek enum value
In Java using the built-in classes:
Calendar calendar = Calendar.getInstance();
calendar.set(year, 1, 1);
return calendar.get(Calendar.DAY_OF_WEEK); // 1 (Sunday) - 7 (Saturday)
In Java using Joda Time:
return new LocalDate(year, 1, 1).getDayOfWeek(); // 1 (Monday) - 7 (Sunday)
This site http://5dspace-time.org/Calendar/Algorithm.html
has a good explanation on how to calculate it even with pencil-and-paper
Wikipedia explains it too
Related
I have one ArrayList:
List<Date> date= ArrayList<Date>();
date.add(2017-07-26 09:27:33);
date.add(2017-07-28 10:11:33);
date.add(2017-07-25 08:27:33);
date.add(2017-07-25 07:27:33);
Now I am testing
date.contains(2017-07-25 11:27:33); //should come true
I want to check on the basis only the only date not time. How can I check only base of date not time?
First of all your code can not compile.
Lets change it to valid java code and compare two date only without time portion:
List<Date> date = new ArrayList();
DateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss", Locale.ENGLISH);
DateFormat compareFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
try {
date.add(format.parse("2017-07-26 09:27:33"));
date.add(format.parse("2017-07-28 10:11:33"));
date.add(format.parse("2017-07-25 08:27:33"));
date.add(format.parse("2017-07-25 07:27:33"));
Date searchedDate = format.parse("2017-07-26 16:27:33");
boolean isExist = date.stream().anyMatch(d -> compareFormat.format(d).equals(compareFormat.format(searchedDate)));
System.out.println(isExist);
} catch (ParseException e) {
e.printStackTrace();
}
Also there are another solutions to compare date without time part, take a look another solutions : How to compare two Dates without the time portion?
I have two dates and I want to compare it.
How can I compare dates?
I have to date objects. Say modificateionDate older updatedDate.
So which is the best practice to compare dates?
Date now conforms to Comparable protocol. So you can simply use <, > and == to compare two Date type objects.
if modificateionDate < updatedDate {
//modificateionDate is less than updatedDate
}
Per #NiravD's answer, Date is Comparable. However, if you want to compare to a given granularity, you can use Calendar's compare(_:to:toGranularity:)
Example…
let dateRangeStart = Date()
let dateRangeEnd = Date().addingTimeInterval(1234)
// Using granularity of .minute
let order = Calendar.current.compare(dateRangeStart, to: dateRangeEnd, toGranularity: .minute)
switch order {
case .orderedAscending:
print("\(dateRangeEnd) is after \(dateRangeStart)")
case .orderedDescending:
print("\(dateRangeEnd) is before \(dateRangeStart)")
default:
print("\(dateRangeEnd) is the same as \(dateRangeStart)")
}
> 2017-02-17 10:35:48 +0000 is after 2017-02-17 10:15:14 +0000
// Using granularity .hour
let order = Calendar.current.compare(dateRangeStart, to: dateRangeEnd, toGranularity: .hour)
> 2017-02-17 10:37:23 +0000 is the same as 2017-02-17 10:16:49 +0000
Swift iOS 8 and up When you need more than simply bigger or smaller date comparisons. For example is it the same day or the previous day,...
Note: Never forget the timezone. Calendar timezone has a default, but if you do not like the default, you have to set the timezone yourself. To know which day it is, you need to know in which timezone you are asking.
extension Date {
func compareTo(date: Date, toGranularity: Calendar.Component ) -> ComparisonResult {
var cal = Calendar.current
cal.timeZone = TimeZone(identifier: "Europe/Paris")!
return cal.compare(self, to: date, toGranularity: toGranularity)
}
}
Use it like this:
if thisDate.compareTo(date: Date(), toGranularity: .day) == .orderedDescending {
// thisDate is a previous day
}
For a more complex example how to use this in a filter see this:
https://stackoverflow.com/a/45746206/4946476
Swift has ComparisonResult with orderedAscending, orderedDescending and same as below.
if modificateionDate.compare(updatedDate) == ComparisonResult.orderedAscending {
//Do what you want
}
Hope this may help you.
Is there a way to change the date and time seen by a specific process as opposed to the entire computer (i.e. the time returned by time() in C, by DateTime.Now in C#, by datetime.now() in Python, by new Date() in JavaScript, by System.currentTimeMillis() in Java, etc.)?
For instance, is there a way to fool a program into thinking it's midnight while it's 7 AM on the rest of the computer, or to make it think it's Christmas or Leap Day while the system clock shows July 18th?
An applicable situation would be when you're writing unit tests and you want to quickly test any special behavior the program has on Christmas or on Leap Day or on the demo's expiration date, and you want to test this behavior without having to use the date changing function in the OS and interfere with programs that rely on the date being correct (much less forcing me to have superuser privileges over the computer).
Previously mentioned Typemock also has an API for C++, which also allows you to fake time, in C++:
TEST_METHOD(FakeCurrentTime)
{
SYSTEMTIME fakeTime;
fakeTime.wYear = 2000;
fakeTime.wMonth = 1;
fakeTime.wDay = 1;
FAKE_GLOBAL(GetSystemTime);
WHEN_CALLED(GetSystemTime(RET(&fakeTime))).Ignore();
SYSTEMTIME now;
GetSystemTime(&now);
Assert::IsTrue(now.wMilliseconds - fakeTime.wMilliseconds == 0);
}
I don't think you can do what you want to do in C#. There aren't any hooks that I know of to make DateTime.Now return arbitrary values out of the box. The standard way to implement unit testing that is time sensitive is to create a time provider interface. This is the approach taken by third party libraries such as Noda Time that values testing time related functions. One such implementation is below (not Noda Time compatible):
public ITimeProvider
{
DateTime CurrentTime { get; }
DateTime CurrentUtcTime { get; }
}
public DefaultTimeProvider : ITimeProvider
{
public DateTime CurrentTime { get { return DateTime.Now; } }
public DateTime CurrentUtcTime { get { return DateTime.UtcNow; } }
}
Then when you want to unit test the code you replace the DefaultTimeProvider implementation with a mock implementation. You can use your favorite mocking framework or just write something like this:
public MockTimeProvider : ITimeProvider
{
private readonly DateTime _currentTime;
private readonly DateTime _currentUtcTime;
public MockTimeProvider(DateTime currentTime, DateTime currentUtcTime)
{
_currentTime = currentTime;
_currentUtcTime = currentUtcTime;
}
public DateTime CurrentTime { get { return _currentTime; } }
public DateTime CurrentUtcTime { get { return _currentUtcTime; } }
}
Disclaimer, I work at Typemock.
You can use Typemock Isolator for this:
[TestMethod]
public void isLicenseExpiredTest()
{
Isolate.WhenCalled(() => DateTime.Now).WillReturn(new DateTime(2017, 5, 4));
bool result = Licenses.IsLicenseExpired();
Assert.IsFalse(result);
}
public static class Licenses
{
public static bool IsLicenseExpired()
{
if (DateTime.Now > new DateTime(2016, 5, 4))
{
return false;
}
else
{
return true;
}
}
}
java.time
Java 8 and later has the java.time framework built in. Supplants the old date-time classes.
Clock
Includes the Clock class. You can override this class to make your own faked current time.
A few alternate implementations are included via static methods. You can ask for a Clock that stays fixed on a single moment you specify. You can shift the current time by some specified amount. And you have the Clock report the current moment rounded to the whole second or minute and so on.
I am trying to test a simple service method. That method mainly just returns the results of a criteria query for which I want to test if it returns the one result or not (depending on what is queried for).
The problem is, that I am unaware of how to right the corresponding test correctly. I am trying to accomplish it via spock, but doing the same with any other way of testing also fails.
Can one tell me how to amend the test in order to make it work for the task at hand?
(BTW I'd like to keep it a unit test, if possible.)
The EventService Method
public HashSet<Event> listEventsForDate(Date date, int offset, int max) {
date.clearTime()
def c = Event.createCriteria()
def results = c {
and {
le("startDate", date+1) // starts tonight at midnight or prior?
ge("endDate", date) // ends today or later?
}
maxResults(max)
order("startDate", "desc")
}
return results
}
The Spock Specification
package myapp
import grails.plugin.spock.*
import spock.lang.*
class EventServiceSpec extends Specification {
def event
def eventService = new EventService()
def setup() {
event = new Event()
event.publisher = Mock(User)
event.title = 'et'
event.urlTitle = 'ut'
event.details = 'details'
event.location = 'location'
event.startDate = new Date(2010,11,20, 9, 0)
event.endDate = new Date(2011, 3, 7,18, 0)
}
def "list the Events of a specific date"() {
given: "An event ranging over multiple days"
when: "I look up a date for its respective events"
def results = eventService.listEventsForDate(searchDate, 0, 100)
then: "The event is found or not - depending on the requested date"
numberOfResults == results.size()
where:
searchDate | numberOfResults
new Date(2010,10,19) | 0 // one day before startDate
new Date(2010,10,20) | 1 // at startDate
new Date(2010,10,21) | 1 // one day after startDate
new Date(2011, 1, 1) | 1 // someday during the event range
new Date(2011, 3, 6) | 1 // one day before endDate
new Date(2011, 3, 7) | 1 // at endDate
new Date(2011, 3, 8) | 0 // one day after endDate
}
}
The Error
groovy.lang.MissingMethodException: No signature of method: static myapp.Event.createCriteria() is applicable for argument types: () values: []
at myapp.EventService.listEventsForDate(EventService.groovy:47)
at myapp.EventServiceSpec.list the Events of a specific date(EventServiceSpec.groovy:29)
You should not use unit tests to test persistence - you're just testing the mocking framework.
Instead, move the criteria query to an appropriately named method in the domain class and test it against a database with an integration test:
class Event {
...
static Set<Event> findAllEventsByDay(Date date, int offset, int max) {
...
}
}
class EventService {
Set<Event> listEventsForDate(Date date, int offset, int max) {
...
return Event.findAllEventsByDay(date, offset, max)
}
}
If there's still value in having the service method as a wrapper (e.g. if it implements some business logic above and beyond the database query), it will now be easy to unit test since it's trivial to mock out the static domain class method call:
def events = [new Event(...), new Event(...), ...]
Event.metaClass.static.findAllEventsByDay = { Date d, int offset, int max -> events }
And that's appropriate since you're testing how the service uses the data it receives and assuming that the retrieval is covered in the integration tests.
Criteria queries are not supported in unit tests. From the mockDomain documentation:
[T]he plugin does not support the mocking of criteria or HQL queries. If you use either of those, simply mock the corresponding methods manually (for example with mockFor() ) or use an integration test with real data.
You'll have to make your test an integration test. You'll see that the exception goes away if you move the test from the test/unit folder to the test/integration folder.
There is some work being done on criteria support in unit tests, and if you're feeling adventurous, you can try it out today. See this mailing list discussion of the DatastoreUnitTestMixin.
LINQ to Entity Framework 4.0. SQL Server.
I'm trying to return a list of objects and one of the columns in the database is varchar(255) and contains dates. I'm trying to cast the value to datetime, but I haven't found the solution to that yet.
Example:
List<MyObject> objects = (from c in context.my_table
where c.field_id == 10
select new MyObject()
{
MyDate = c.value // This is varchar, want it to be datetime
}).ToList();
Is this not possible?
Update. This is LINQ to Entity. When trying to convert to DateTime I get:
LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method, and this method cannot be translated into a store expression.
The answer is it's not currently possible with Entity Framework. With LINQ itself it is, just not supported with Entity Framework.
You want DateTime.Parse(c.value) which will take a string containing a date and create a DateTime object out of it.
you can do like this
Date=DateTime.Parse(text)
read, And the best bet would be using your result and then Converting to date time. Like below,
static void Main(string[] args)
{
Console.WriteLine(getme());
Console.ReadLine();
}
private static DateTime getme()
{
List<string> ss = new List<string>();
ss.Add("11/11/2010");
var r = from l in ss
select new { date = Convert.ToDateTime(l) };
return r.FirstOrDefault().date;
}