Strange FormatException after upgrading in VS 2010 - c#-4.0

I get this FormatException after i upgraded to VS 2010. Not anything really special.
Code:
private void ManageDateEditControls()
{
apoDateEdit.DateTime = DateTime.Parse(string.Format("01/{0}/{1}", DateTime.Now.Month-1, DateTime.Now.Year));
eosDateEdit.DateTime = DateTime.Parse(string.Format("{0}/{1}/{2}", GetLastDayOfMonth(DateTime.Now.Month + 1),
DateTime.Now.Month - 1, DateTime.Now.Year)); <-- FormatException occurs in this line.
}
private static int GetLastDayOfMonth(int month)
{
// set return value to the last day of the month
// for any date passed in to the method
// create a datetime variable set to the passed in date
DateTime dtTo = new DateTime(DateTime.Now.Year, month, 1);
// overshoot the date by a month
dtTo = dtTo.AddMonths(1);
// remove all of the days in the next month
// to get bumped down to the last day of the
// previous month
dtTo = dtTo.AddDays(-(dtTo.Day));
// return the last day of the month
return dtTo.Day;
}
Lets say you get now if you run this 31/6/2010. I think its a valid date.
I have tested the date that is generated and its ok...this project never had this problem while was working in VS 2008.
Any ideas?

Your FormatException is caused by passing 31/6/2010 as an argument to DateTime.Parse(). 31/6/2010 is not a valid date - there are only 30 days in June.
If you need the last day in any month, you would be better off using the DateTime.DaysInMonth() method. It takes both the month and year as arguments so it can deal with leap years.

Related

Return new date after adding the number to the today's date in node js

I have a logical question may be it sound simple but I am facing problem while solving this. Situation is I have a number of days that is expire days now by using that number I have to create a expire date, let me give you one example.
if today's date is 25-07-2020 and no.of expire days is 10 then expire date should be 04-08-2020
I want to this to implement in node js, right now I am getting today's date using Date method.
const today = new Date().toISOString().replace(/\T.+/, '')
This returns today's date but now I am confused how can I get my expire date after adding no.of days.
You need to use setDate here
var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 10);
console.log(currentDate) //this will have the new date
You can do this with a function:
function addDays(date, days) {
const copy = new Date(Number(date))
copy.setDate(date.getDate() + days)
return copy
}
const date = new Date();
const newDate = addDays(date, 10);
So, you can't add 10 days by simple manipulation of the Date as a string, since you'd need to account for all sorts of edge cases (change of month, change of year, time-zone changes).
There are lots of good libraries out there that can help you, like date-fns or Moment.js.
However, if you want to do this without a library, it's quite straightforward:
const now = +new Date(); // Gets the date as ms since epoch
const expiry = new Date(now + (10 * 24 * 60 * 60 * 1000)); Adds 10 days worth of ms

Comparing Time Strings in Swift

In the app I am making when the view loads I want an object to be deleted in the background whenever the current time is greater than the given time. Otherwise if the current time is less than the given time the object loads normally. This is working fine for any time within the hour for example if the current time is 9:30 PM and the given time is 9:45 PM it works fine, but if the current time is 9:30 PM and the given time is 11:45 PM for some reason it doesn't know how to compare the hour so it doesn't work. Here is my code:
if timeString > End {
self.SpotterMap.removeAnnotation(SpotAnnotation)
let endTime = End
let query:PFQuery = PFQuery(className: "SpotInfo")
query.whereKey("spotendtime", equalTo: endTime)
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for object in objects {
object.deleteInBackground()
}
}
})
print ("spot removed")
}
Can anyone give a solution to my problem?
Thanks
If you are going to work with times, you need to work with the NSDate type representation of your dates for the best accuracy, not a string one.
You will need to change your parse class spotInfo and add a column of type date, lets say you call it "realSpotEndTime".
To compare the times use .compare directly on the NSDates, if the dates return true when ordered ascending, it means that the first date comes before the second one. So your if statement would become;
(note: to get the real current time, you need to instantiate NSDate() right before comparison)
If this returns true and executes it means that the current time on the phone is less compared to the End time, remember, End needs to be in NSDate type as well, not string
let currentTime = NSDate()
//currentTime < End
if (currentTime.compare(End) == .OrderedAscending) {
...
query.whereKey("realSpotEndTime", lessThanOrEqualTo: currentTime)
}
or, alternatively you could do check if the current time is past the end time by
//End < currentTime
if (End.compare(currentTime) == .OrderedAscending) {
// fix parse query here
}

Calculate the duration between now and next local time

I need to determine the duration between now and the next occurrance of a local time. Here's what I've got:
Duration GetDuration(IClock clock, LocalTime time, DateTimeZone zone)
{
// get the current time in this zone
var now = clock.Now.InZone(zone);
// find the time in our zone today
var timeToday = zone.AtLeniently(now.Date + time);
// find the time in our zone tomorrow
var timeTomorrow = zone.AtLeniently(now.Date.PlusDays(1) + time);
// get the next occurrance of that time
var next = new[]{timeToday, timeTomorrow}.Where(x => x > now).Min();
// calculate the duration between now and the next occurance of that time
var duration = next.ToInstant() - now.ToInstant();
Debug.Assert(duration > Duration.Zero);
return duration;
}
And a test to get the duration between now and the next instant of 5PM eastern time:
var duration = GetDuration(
SystemClock.Instance,
new LocalTime(17,00),
DateTimeZoneProviders.Tzdb["US/Eastern"]);
My question is, since I'm new to NodaTime, am I taking any unnecessary steps or missing any shortcuts?
This code is a bit more long-winded than it needs to be - I'd do most of the work in the "local" context, and only convert back to the time zone when you know the LocalDateTime you want to map.
var now = clock.Now.InZone(zone);
// Change this to <= time if you want it to be a "strictly next".
var nextDate = now.TimeOfDay < time ? now.Date : now.Date.PlusDays(1);
return zone.AtLeniently(nextDate + time).ToInstant() - now.ToInstant();
AtLeniently will always return a value which is no earlier than the given LocalDateTime (it returns the later of two ambiguous options, and the start of the interval after a skipped time), so you don't need to worry about DST transitions.
As an aside, feedback about whether the ToInstant() calls in the last line are annoying would be useful. I'd at least consider adding a Duration operator-(ZonedDateTime, ZonedDateTime) to 2.0.
The most easy way is like this:
LocalDate now = LocalDate.now();
LocalDate now2 = now.plusDays(4);
ChronoUnit.DAYS.between(now, now2);

How do I display todays date in Node.js Jade?

I am new to Node.js and Jade and I have tried to use #{Date.now()} and it's giving me numbers. How do I display the date in mm/dd/yy format?
You can use moment.js
First, add moment to your express application locals
express = require('express');
...
app = express();
app.locals.moment = require('moment');
Then you can use moment within a jade template like this:
p #{moment(Date.now()).format('MM/DD/YYYY')}
Moment takes Date.now() by default, so yo can also write:
p #{moment().format('MM/DD/YYYY')}
Sources:
Making use of utility libraries in server-side Jade templates
Moment.js
This is old, but I do the following:
return (new Date()).toLocaleDateString()
Returns a date 'mm/dd/yyyy' format, in no additional libs required.
Or you could use the moment.js library to handle dates and format them accordingly to your needs
I actually started using date-util which is 2 parts both clientside and server side.
URL https://github.com/JerrySievert/node-date-utils
Using within a Browser
<script type="text/javascript" src="date-utils.min.js"></script>
Using with Node.js
$ npm install date-utils
require('date-utils');
Note: This did not work in the REPL before Node.js 0.6 due to how Node.js handles context in the REPL.
Static Methods
Date.today(); // today, 00:00:00
Date.yesterday(); // yesterday, 00:00:00
Date.tomorrow(); // tomorrow, 00:00:00
Date.validateDay(day, year, month); // true/false whether a date is valid
Date.validateYear(year); // true/false whether a year is valid
Date.validateMonth(month); // true/false whether a month is valid
Date.validateHour(hour); // true/false whether an hour is valid
Date.validateMinute(minute); // true/false whether a minute is valid
Date.validateSecond(second); // true/false whether a second is valid
Date.validateMillisecond(millisecond); // true/false whether a millisecond is valid
Date.compare(date1, date2); // -1 if date1 is smaller than date2, 0 if equal, 1 if date2 is smaller than date1
Date.equals(date1, date2); // true/false if date1 is equal to date2
Date.getDayNumberFromName(name); // su/sun/sunday - 0, mo/mon/monday - 1, etc
Date.getMonthNumberFromName(name); // jan/january - 0, feb/february - 1, etc
Date.isLeapYear(year); // true/false whether the year is a leap year
Date.getDaysInMonth(monthNumber); // number of days in the month
Instance Methods
d.clone(); // returns a new copy of date object set to the same time
d.getMonthAbbr(); // abreviated month name, Jan, Feb, etc
d.getMonthName(); // fill month name, January, February, etc
d.getUTCOffset(); // returns the UTC offset
d.getOrdinalNumber(); // day number of the year, 1-366 (leap year)
d.clearTime(); // sets time to 00:00:00
d.setTimeToNow(); // sets time to current time
d.toFormat(format); // returns date formatted with:
// YYYY - Four digit year
// MMMM - Full month name. ie January
// MMM - Short month name. ie Jan
// MM - Zero padded month ie 01
// M - Month ie 1
// DDDD - Full day or week name ie Tuesday
// DDD - Abbreviated day of the week ie Tue
// DD - Zero padded day ie 08
// D - Day ie 8
// HH24 - Hours in 24 notation ie 18
// HH - Padded Hours ie 06
// H - Hours ie 6
// MI - Padded Minutes
// SS - Padded Seconds
// PP - AM or PM
// P - am or pm
d.toYMD(separator); // returns YYYY-MM-DD by default, separator changes delimiter
d.between(date1, date2); // true/false if the date/time is between date1 and date2
d.compareTo(date); // -1 if date is smaller than this, 0 if equal, 1 if date is larger than this
d.equals(date); // true/false, true if dates are equal
d.isBefore(date); // true/false, true if this is before date passed
d.isAfter(date); // true/false, true if this is after date passed
d.getDaysBetween(date); // returns number of full days between this and passed
d.getHoursBetween(date); // returns number of hours days between this and passed
d.getMinutesBetween(date); // returns number of full minutes between this and passed
d.getSecondsBetween(date); // returns number of full seconds between this and passed
d.add({ milliseconds: 30,
minutes: 1,
hours: 4,
seconds: 30,
days: 2,
weeks: 1,
months: 3,
years: 2}); // adds time to existing time
d.addMilliseconds(number); // add milliseconds to existing time
d.addSeconds(number); // add seconds to existing time
d.addMinutes(number); // add minutes to existing time
d.addHours(number); // add hours to existing time
d.addDays(number); // add days to existing time
d.addWeeks(number); // add weeks to existing time
d.addMonths(number); // add months to existing time
d.addYears(number); // add years to existing time
You will need to use the methods on the Date object to achieve what you're after. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
For example, the code below should do what you need:
var dateNow = new Date();
var dd = dateNow.getDate();
var monthSingleDigit = dateNow.getMonth() + 1,
mm = monthSingleDigit < 10 ? '0' + monthSingleDigit : monthSingleDigit;
var yy = dateNow.getFullYear().toString().substr(2);
var formattedDate = mm + '/' + dd + '/' + yy;
So if you were using say jade with express and node you could do something like:
res.render('jadeTemplateName', {
dateNow: function() {
var dateNow = new Date();
var dd = dateNow.getDate();
var monthSingleDigit = dateNow.getMonth() + 1,
mm = monthSingleDigit < 10 ? '0' + monthSingleDigit : monthSingleDigit;
var yy = dateNow.getFullYear().toString().substr(2);
return (mm + '/' + dd + '/' + yy);
}
})
and in your jade template say if you wanted to add the date to a span:
span Today's date is #{dateNow()}
add the class .post-date to a tag holding the date
document.addEventListener('DOMContentLoaded', function() {
var list = document.getElementsByClassName('post-date');
// get the number of selected elements
// iterate over elements and output their HTML content
for (var i=0; i<list.length; i++){
//console.log(list[i].innerHTML);
var string=list[i].innerHTML;
var length = 15;
var trimmedString = string.substring(0, length);
list[i].innerHTML=trimmedString ;
}
})
I found a solution
1.Create a function in pug using - syntax
2.pass the varible to the function when pug.js is binding variables to the pug template
-function prettyDate(dateString){
-var date = new Date(dateString);
-var d = date.getDate();
-var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
-var m = monthNames[date.getMonth()];
-var y = date.getFullYear();
-return d+' '+m+' '+y;
-}
3.span.post-date #{prettyDate(val.date)};

get previous date in J2ME

I want to get the date of previous month in J2ME.
I have found this code :
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -1); //one year back
c.add(Calendar.MONTH, -1);// then one month
but this is working in Java SE not J2ME, please if anyone can help me find the corresponding method or class in J2ME?
Calendar does not have method add.
c.set(Calendar.MONTH, -1)
Means you set value -1 at field MONTH.
Your solution is
// get current month
int m = c.get(Calendar.MONTH);
// decrement it
if (--m < 0) {
// if was january, must become december of past year
m = 11;
// set year to previous
c.set(Calendar.YEAR, c.get(Calendar.YEAR) - 1);
}
// set new value "m" to field MONTH
c.set(Calendar.MONTH, m);
Please refer to http://docs.oracle.com/javame/config/cldc/ref-impl/midp2.0/jsr118/index.html
for documentation. You should't work without it unless you know all you need.

Resources