retrievind date in asp.net - asp.net

I need to retrieve the current date in asp.net and then compare that with the date given by the user in textbox1.text(mm/dd/yyyy format), if date date given is greater than current date then error else add 4months2days with that date and display it in textbox2.text.
help me please,
thanking you guys,
Indranil

DateTime dateToCompare;
if(DateTime.TryParse(textbox1.text, out dateToCompare))
{
DateTime current = DateTime.Now;
TimeSpan ts = current - dateToCompare;
if (ts.Ticks < 0)
{
//display error
}
else
textbox2.text = dateToCompare.AddMonths(4).AddDays(2).ToString("mm/dd/yyyy");
}
}

I'm not going to write your code, but in .NET you can use ToString to specify a date format, TryParse to get a date out of a string. And AddDays, AddMonths etc to manipulate a date.
In javascript, there's no simple way to format output, but you can use getMonth etc to prompt the individual values and concatenate a string from that. You can use a combination of getDate and setDate to manipulate dates. It automatically corrects for new months, i.e. if you run myDate.setDate( myDate.getDate() + 60 ) it'll actually increment by 60 days; you won't end up with a weird date like May 74th.
Keep in mind that months in javascript are zero-based, ie January is 0, February is 1, etc.
You can create a new date in javascript by new Date(yy, mm, dd) or new Date('yy/mm/dd'), so you could string-manipulate an input and create a date from that.
To compare two dates, you can subtract one from the other, and get the difference in milliseconds.
if ( dateA - dateB < 0 ) // dateB is greater than dateA (occurrs later)
and
var diff = Math.abs(dateA - dateB) // difference in ms, no matter which date is greater

DateTime date1 = new DateTime();
if(DateTime.TryParse(textbox1.text, out date1)){
if (date1.CompareTo(DateTime.Now) > 0)
{
//Error code here
}else
{
textbox2.text = date1.AddMonths(4).AddDays(2);
}
}

Related

how calculate difference or compare(is bigger or not) between to data(Jalali calendar)

I use two ngb-datepicker in a page, of course jalali calendar, and bind to these two model:
dateModelFrom: NgbDateStruct;
dateModelTo: NgbDateStruct;
after user select dates, i have 2 jalali date with ngb date structure:
dateModelFrom = {day: 1, month: 1, year: 1398}
dateModelTo = {day: 3, month: 1, year: 1398}
now, I need to calculate difference between two dates, and check if fromDate is less than toDate or not.
i can use (https://github.com/alihoseiny/ngx-persian) or (https://momentjs.com/) and convert these two date and then calculate, but this can not be good, I think must be shorter solution.
also i know there is NgbDateNativeAdapter service(https://ng-bootstrap.github.io/#/components/datepicker/api#NgbDateNativeAdapter), i try to convert to javascript Date, and then calculate, but output is same as input:
let toDay:NgbDateStruct = this._persianNgbCalendar.getToday();;
let _toDay:Date = this._ngbDateNativeAdapter.toModel(toDay);
In the documenation from ngb-datepicker you will find an example for a range picker and there is a implementation for comparing two dates. Also you can check the stackblitz for better understanding.
Example:
<ngb-datepicker #dp (select)="onDateSelection($event)" [displayMonths]="2" [dayTemplate]="t" outsideDays="hidden"></ngb-datepicker>
In your onDateSelection function you can compare two dates:
onDateSelection(date: NgbDate) {
if (!this.fromDate && !this.toDate) {
this.fromDate = date;
} else if (this.fromDate && !this.toDate && date.after(this.fromDate)) {
this.toDate = date;
} else {
this.toDate = null;
this.fromDate = date;
}
}

moment.js Timezone Parsing and Comparison

I'm receiving timestamps in the following format '2016-08-17T14:00:00-04:00', which I can parse in moment with moment('2016-08-17T14:00:00-04:00', 'YYYY-MM-DDTHH:mm:ssZ').
But the problem is that I want to print out .format('LLLL') and have it read Wednesday, August 17, 2016 10:00 AM, i.e. subtracting -04:00 from 14:00:00 (NY from UTC). It appears that there is a _tzm: -240 property in the moment object that looks like it holds that -4 hours value, but how do I use that property?
The other goal is to be able to pass in the current time and test if it is between the startDate and endDate variables below. I am guessing if I can convert both to NY-EST I can do this, but I can't seem to get moment to accept the timezone parameter.
Any thoughts?
var moment = require('moment');
// Timestamp strings from API
var startDate = '2016-08-17T14:00:00-04:00';
var endDate = '2016-08-17T15:00:00-04:00';
// Create a range from the start and end dates
var range = moment().range(new Date(startDate), new Date(endDate));
// Get the current time
var currentTime = new Date();
// Does the current time fall within the range b/w the start and end dates
range.contains(currentTime);
A solution I found is below. Adding the value from momentObj._tzm to the parsed date.
module.exports.convertDateToProperTimezone = function (dt) {
var _m = moment(dt, 'YYYY-MM-DDTHH:mm:ssZ');
return _m.add(_m._tzm, 'minutes');
};

Convert fulltime to minutes C#

I need convert GMT time 14:21:34 to minute (14*60+21=861 minutes)
I know there is a inbuilt function which convert min to HH:MM
Use TimeSpan.FromMinutes:
var result = TimeSpan.FromMinutes(1815);
Is there an easy way to do this that I am missing?
Two options to get to a TimeSpan:
1) Parse it as a DateTime (specifying a format), then use DateTime.TimeOfDay to get a TimeSpan
var dt = DateTime.ParseExact(
"14:21:34",
#"HH\:mm\:ss",
CultureInfo.InvariantCulture);
var ts = dt.TimeOfDay;
I like this option as it sounds like the value you've got is meant to be a time of day.
2) Parse it as a TimeSpan:
var ts = TimeSpan.ParseExact(
"14:21:34",
#"hh\:mm\:ss",
CultureInfo.InvariantCulture);
Once you have a TimeSpan, use TotalMinutes (which returns a double) to get the number of minutes. For example:
Console.WriteLine((int) ts.TotalMinutes); // 861

How to convert string to datetime format classic asp

I have one variable
Dim tt="2008-10-20 10:00:00.0000000"
I want to change it into date,
Try CDATE(tt) see http://www.w3schools.com/vbscript/func_cdate.asp. I used
vbscript cdate
as keywords at Google. There were more results.
Edit: Based on the comment below (I'm sorry for mixing up), using
FormatDateTime(date,format)
Format contains following constants:
0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if
specified: hh:mm:ss PM/AM.
1 = vbLongDate - Returns date: weekday, monthname, year
2 = vbShortDate - Returns date: mm/dd/yy
3 = vbLongTime - Returns time: hh:mm:ss PM/AM
4 = vbShortTime - Return time: hh:mm
(copied from http://www.w3schools.com/vbscript/func_formatdatetime.asp)
This link, (MS CDate page), explains that:
adate = CDate(astring)
converts a string into a date object. For there, you can format it with the FormatDateTime function
str = FormatDateTime(Date)
the FormatDateTime function is "smart" -- it will format as date and time if both are present, otherwise it will format with whichever of date or time is present.
I propose a safe solution which returns the result only if the conversion is successful:
s="2008-10-20 10:00:00.0000000"
On Error Resume Next
d=CDate(Left(s,19))
On Error Goto 0
if not IsEmpty(d) then MsgBox d
Try it for a non-valid date or non-valid format. The result will be empty.
s="2008-02-31 10:00:00"
In same contexts, it is necessary to initialize the variable collecting result of CData. I recommend to initialize it as Empty. Example below shows such case - counting valid dates in a string array:
Lines = array("2008-10-20 10:00:00.0000000", "2008-10-20 10:00:00", "", "2008-02-31", "Today", "2017-02-7")
On Error Resume Next
Count=0
for each Line in Lines
d=Empty
d=CDate(Line)
if not IsEmpty(d) then Count=Count+1
next
On Error Goto 0
MsgBox "Number of valid dates is "&Count
The correct answer is 2. Without initialization we get 5 as the CDate does not do anything on error so variable keeps the value from a recent iteration in the loop.
If do not need your milliseconds, your could use the following:
<script type="text/vbscript">
s="2008-10-20 10:00:00.0000000"
arr= Split(s, ".")
d=CDate(arr(0))
document.write(d)
</script>
I believe cdate is dependent on local settings to parse the string. This is no good in many situations.
To avoid this you need to use
DateSerial()
and if needed add any time components to the result separately.
The date literal in classic asp is unreliable. If the first or second part is greater than 12, it takes that value for day, the other as month. If both parts are less than 12, the interpretation is unpredictable: sometimes american and sometimes british.
A work-around is to force the entry of dates into separate fields or use a date entry module which can set the date into british or american style.
A date literal should be treated as american and use a function to convert that into a date variable using Dateserial().
function amerdate(str)
'str 3/5/2023 form: in american format: use for calculations including date
Dim d
d = Split(str, "/")
amerdate = Dateserial(d(2), d(0), d(1))
end function
Use only american date in calculations like Dateadd() etc.
someday = "3/5/2023" '5th march, american date literal
nextday = Dateadd("d", 1, amerdate(someday))
Whenever a date display is required, convert to british date and show it.
function britdate(str)
'str: 3/5/2023 form: display in british form. not for calculations
Dim d
d= Split(str, "/")
britdate = d(1) & "/" & d(0) & "/" & d(2)
end function

comparison of two dates

how to compare values of 2 dates using actionscript
i executed this code in my program..
var time1:Date = new Date(Number(fromDate.substr(0,4)),Number(fromDate.substring(5,7))-1, Number(fromDate.substring(8,10)));
var time2:Date = new Date(Number(toDate.substr(0,4)),Number(toDate.substring(5,7))-1, Number(toDate.substring(8,10)));
if(time1.getTime() > time2.getTime())
{
Alert.show(time1 + ” is after ” + time2);
}
im getting error: Error: Unexpected end of token stream
AS3 doesn't support a time delta class like Python so this can actually be a little tricky. There are lots of things to be worried about when comparing dates:
daylight savings time (when the clocks change one hour in certain countries Spring and Fall)
time-zones
leap-years
The roughest way to do things is just to use the time property of a date object. This way you can get an accurate difference between two dates expressed in milliseconds:
var date1:Date = new Date(2001, 9, 12); // Oct. 12, 2001
var date2:Date = new Date(2010, 5, 22); // Jun. 22, 2010
var differenceInMilliseconds:Number = date2.time - date1.time;
Using this time property you can do things like check if one date is before or after another date. You can also do rough calculations on the distance between two dates by defining some constants:
const MILLISECOND_PER_SECOND:int = 1000;
const SECOND_PER_MINUTES:int = 60;
const MINUTES_PER_HOUR:int = 60;
const HOURS_PER_DAY:int = 24;
// ... etc ...
var differenceInSeconds:Number = differenceInMilliseconds / MILLISECOND_PER_SECOND;
var differenceInMinutes:Number = differenceInSeconds / SECOND_PER_MINUTES;
var differenceInHouse:Number = differenceInMinutes / MINUTES_PER_HOUR;
var differenceInDays:Number = differenceInHouse / HOURS_PER_DAY;
Once you get to the level of days you could get problems with daylight savings time since the change of 1 hour can make it seem like a full day has passed when it really hasn't. After days and into weeks or months you run into leap year problems.
Assuming your string processing code correctly gives you valid date objects, just use the ObjectUtil.dateCompare function to compare 2 dates:
http://livedocs.adobe.com/flex/3/langref/mx/utils/ObjectUtil.html#dateCompare%28%29
if( ObjectUtil.dateCompare(date1, date2) == 1 ){}
I'm pretty sure that the return types defined in the ASDocs are wrong.
It'll actually return -1 if a is null or before b; 1 if b is null or before.
If you have two dates as Date objects already, just compare them. e.g. a.getTime() > b.getTime().
If they are strings, see their format is acceptable by the default Date.parse() function. If not, you may have other work to do.
Let's see your values first, shall we?
private function differenceBetweenDates(date1:Date, date2:Date):Number{
var MS_PER_DAY:uint = 1000 * 60 * 60 * 24;
var tempDate:Date = new Date(date2.time - date1.time);
var difference:Number =
Math.abs(Math.round((tempDate.time / MS_PER_DAY)));
return difference;
}
I have achieved comparing dates succesfully using below code:
//here i have to compare two dates ,these are startdate and enddate.
// gets millisecs counts from 1970 midnight till sellected start date
var Starttimecounts : Number = popJobWin.DFStartDate.selectedDate.time;
// gets millisecs counts from 1970 midnight till sellected end date
var Endtimecounts : Number = popJobWin.DFEndDate.selectedDate.time ;
if (Starttimecounts > Endtimecounts)
{
Alert.show('end date should not lesser than start date..wrong!');
//replace your logic here
}
else
{
Alert.show('correct!');
//replace your logic here
}

Resources