I am fetching the date from my Django backend which comes like this: 2016-03-31
In my angular controller I want to compare it with today's date and if they are similar I want to deactivate a button.
I tried new Date() which gives me something like Thu Mar 31 2016 08:59:01 GMT+0200 (W. Europe Daylight Time)
How can these two dates be compared to achieve my goal?
ehhhhh... i think currently we could only do a manual formatting
see this one: How to format a JavaScript date
For your reference, below is what i did though:
$scope.formatDate = function(date){
var newDate = new Date(date);
var year = newDate.getFullYear();
var month = (newDate.getMonth() + 1).toString(); //add 1 as Jan is '0'
var day = newDate.getDate().toString();
month = month.length > 1? month: '0'+month;
day = day.length > 1? day: '0'+day;
$scope.date = day + '/' + month + '/' + year;
}
If you want to compare the date with now you can do the following:
var now = new Date().getTime();
var compareDate = new Date('2016-03-31').getTime();
if(now > compareDate){
//greater
}else if(now < compareDate){
//less
}else{
//equal
}
Just add what you need to the scope and then you could do something like:
ng-disabled="compareDate === today"
Related
Actually in my app. I am trying to display current date & time in a specific format like this " 27/02/2019 1:40 PM ". I have done this by making use of custom formatting codes. But what i actually need is, I need to achieve this by making use of libraries.
Thanks for helping.!
Using this:(Manually formatting Date & Time)
var d = new Date();
var date = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
var hours = d.getHours();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12;
var min = d.getMinutes();
min = min < 10 ? '0'+min : min;
var result = date + '/' + month + '/' + year + ' ' + hours + ':' + min + ' ' + ampm;
console.log(result); //Prints DateTime in the above specified format
Use moment.js https://momentjs.com/
moment().format('DD/MM/YY h:mm A') will give you your desired output.
I am very new to angular JS but since morning struggling with this.
I have a datepicker with "MM/yyyy" format, the date value returned here is first day of month.
i.e. February 1, 2017 but i want the date as February 28, 2017 i.e last day of month.
Just to update i am using moment function.
Please suggest some work around for the same!
I infer from your question that you are using momentjs.
This lib provides you with a built in function endof
const date = new Date(2017, 1) // 1st Feb
moment(date).endOf('month');
This should handle most cases directly including leap years
If you have a JavaScript Date instance d, you can simply use
const d = new Date(2017, 1) // 1st Feb
d.setMonth(d.getMonth() + 1)
d.setDate(d.getDate() - 1)
console.info(d.toLocaleString())
Now d will be the last day of the month.
Note: this easily handles year boundaries without any extra code. For example
const d = new Date(2017, 11) // 1st Dec
console.info('Before', d.toLocaleString())
d.setMonth(d.getMonth() + 1)
d.setDate(d.getDate() - 1)
console.info('After', d.toLocaleString())
You just need add 1 month to the date, and then substract 1 day. Here's an example:
// Let's suppose the date selected from the picker was February 1st, 2017
// Remember months in JS are zero-index based, so 0=Jan, 1=Feb, etc.
var selectedDate = new Date(2017, 1, 1);
var month = selectedDate.getMonth();
var year = selectedDate.getFullYear();
month ++;
if(month > 11){ // Last month number is 11 (December)
month = 0; // January
year ++;
}
var oneMonthAheadDate = new Date(year, month, 1);
var lastDayOfSelectedMonthDate = new Date(oneMonthAheadDate.getTime() - (1000 * 3600 * 24)); // We substract 1 day (1000 ms x 3600 secs in an hour x 24 hours in a day)
Your needed date will be in lastDayOfSelectedMonthDate
I receive a number representing a date in ddmmyy format eg.: 250615 i need transform into this format : 25/06/15.
I canot use the angular date filter because i receive a number.
I try to use slice in this way but only print the first number
{{ singularitem.Dia.slice(0,2)}} {{ singularitem.Dia.slice(2,2) }} {{ singularitem.Dia.slice(-2,2) }}
How can it be done ?
ThankĀ“s in advance
Since you can't use the date filter, just create your own filter, doing whatever you want it to do:
app.filter('transformDate', function() {
return function(date) {
// Split string at every second character and combine them again with a `/` in between
return date.match(/.{1,2}/g).join('/');
}
})
Usage:
{{date | transformDate}}
Plunker: http://plnkr.co/edit/uBeT0eHOoAlHDUWydOpM?p=preview
You can go for a vanilla javascript function. If your format is always dd/mm/yy check this function:
(function () {
var date = "250615";
date = date.slice(0, 2) + "/" + date.slice(2,4) + "/" + date.slice(4,6);
console.log(date);
})()
FIDDLE
Slice is a prototype function of Strings and Arrays, not numbers. You need to convert your number to string first.
If you want to convert that number to a date object, you'd need:
function parseDate(dateAsNumber) {
var dateAsString = "" + dateAsNumber;
var day = Number(dateAsString.substr(0, 2));
//months are index 0
var month = Number(dateAsString.substr(2,2)) - 1;
//assumming all dates are 2000+ since you only get 2 digits
var year = Number(dateAsString.substr(4,2)) + 2000;
var date = new Date(year, month, day);
return date;
}
Calling parseDate(250615) returns Thu Jun 25 2015 00:00:00 GMT-0700 (Pacific Daylight Time)
I've tried the angular docs of {{someDate | date:'params'}}, however; This doesn't work if someDate is in this format yyyy-MM-dd HH:mm:ss.
How would I convert yyyy-MM-dd HH:mm:ss to say just yyyy using angularjs.
The date filter is designed to handle multiple input types including date objects and common date strings. If your date string is not recognized by the provided date filter, I would just write my own filter. It would look something like this...
myapp.filter('toYear', function () {
return function (dateString) {
var dateObject = new Date(dateString);
return dateObject.getFullYear();
};
});
You can use it like this...
{{someDate | toYear}}
You can define a custom format as follows
Date.prototype.customFormat = function(){
return this.getMonth() +
"/" + this.getDate() +
"/" + this.getFullYear();
}
//usage
> var d = new Date()
Fri Mar 14 2014 15:39:07 GMT+0000 (GMT Standard Time)
> d.customFormat()
'2/14/2014'
More details https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
I actually fixed the solution here:
app.filter('timestampToISO', function() {
return function(input) {
input = new Date(input).toISOString();
return input;
};
});
http://bit.ly/1iJAV8G
UPDATE:
To implement you add this to the view:
{{someSQLTIMESTAMP | timestampToISO | date}}
Angular js date object doesn't support to convert from MySql date format to timestamp directly. So need to convert it to acceptable format from YYYY-mm-dd H:i:s to YYYY/mm/dd H:i:s and then convert it to a timestamp.
You may try the below snippet to convert Mysql date format YYYY-mm-dd H:i:s to timestamp using AngularJs filter
app.filter("mysqlDateFormatToTimestamp", function(){
return function(date){
var date1 = date2 = date3 = timestamp = hours = minutes = seconds = '';
date1 = date.split(':');
date2 = date1[0].split(' ');
date3 = date2[0].split('-'); // Change it based on your format
if( date1.length == 1 && date2.length == 1 ){
hours = '00';
minutes = '00';
seconds = '00';
}else{
hours = parseInt(date2[1]);
minutes = parseInt(date1[1]);
seconds = parseInt(date1[2]);
}
timestamp = new Date(parseInt(date3[0]), parseInt(date3[1])-1, parseInt(date3[2]), hours, minutes, seconds);
return timestamp;
}
});
Now, You may use this filter wherever the date format you want, and you may change the params as you like.
{{ '2016-07-07 05:27:30' | mysqlDateFormatToTimestamp | date:'LLLL dd, yyyy HH:mm:ss'}}
// results would comes like "July 07, 2016 05:27:30"
{{ '2016-07-07 05:27:30' | mysqlDateFormatToTimestamp | date:'yyyy'}}
// results would comes like "2016"
I have an algorithm which scans through data read from a .csv file(approx 3700 lines) and assess's which trading week of the year each entry is in by running a count++ for every Sunday of that year and assigning the count value as the trading week when the date falls within that week.
It's working but performance is lagging. It is the 3rd function running using Task.Factory.StartNew (I have also tried parallel.Invoke).
Results of timing tests.
before: 00:00:05.58
after: 00:00:23.27
UPDATE
Added break after each trading week is set. Time improved but still slow.
new time: 00:00:15.74
For our purposes the 1st week of the year is week 1(not 0) and is defined as from the first day of the year until the Sunday. If the first day of the year is a Sunday the length of week 1 is 1 day.
private void SetDefiniteWeeks()
{
string FileLoc = FilePath + Market + ".csv";
string[] Data = File.ReadAllLines(FileLoc);
var FileData = from D in Data
let DataSplit = D.Split(',')
select new
{
Date = DateTime.Parse(DataSplit[0]),
ClosingPrice = double.Parse(DataSplit[4])
};
//assign each date to it's relevant week
TradingWeek TW;
List<TradingWeek> tradingWeek = new List<TradingWeek>();
foreach (var pe in FileData)
{
// DateTime dt = pe.Date;
int Year = pe.Date.Year;
string End_of_Week = "Sunday";
int WeekCount = 0;
DateTime LoopDate_Begin = new DateTime(Year,1,1);
DateTime LoopDate_End = new DateTime(Year,12,31);
do
{
if (LoopDate_Begin.DayOfWeek.ToString() == End_of_Week)
{
WeekCount++;
if (LoopDate_Begin.DayOfYear > pe.Date.DayOfYear && LoopDate_Begin.DayOfYear < (pe.Date.DayOfYear + 7))
{
TW = new TradingWeek { Week = WeekCount, Date = pe.Date };
tradingWeek.Add(TW);
break;
}
}
LoopDate_Begin = LoopDate_Begin.AddDays(1);
} while (LoopDate_Begin.Date.ToString() != LoopDate_End.Date.ToString());
}
}
Please help.
UPDATE
NEW TIME
00:00:06.686
A vast improvement. Thanks all for your help.
Revised code:
CalendarWeekRule cw = CalendarWeekRule.FirstDay;
var calendar = CultureInfo.CurrentCulture.Calendar;
var trad_Week = (from pe in FileData
select new TradingWeek
{
Date = pe.Date,
Week = (calendar.GetWeekOfYear(pe.Date, cw,DayOfWeek.Sunday))
}).ToList();
Im not sure if this is what you want but after reading the comments I got the feeling that this might work (?)
var calendar = CultureInfo.CurrentCulture.Calendar;
var tradingWeek = (from pe in FileData
select new TradingWeek
{
Date = pe.Date,
Week = calendar.GetWeekOfYear(pe.Date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
}).ToList();
Edit: Changed to CalendarWeekRule.FirstDay since it's (more?) what OP is looking for.
Three quick thoughts:
Why are you only adding one day each time and checking to see if it's Sunday. Surely once you have found your first Sunday you can add seven days to find the next one?
If you order your pes by DateTime before you start then you don't need to restart at the beginning of the year for each one, you can pick up where you left off.
As Nicolas says, break after adding the trading week. No need to go through the rest of the year after you already know what the answer is.
I guess you'll end up with something like this (may or may not actually work, but should be close enough)
TradingWeek TW;
List<TradingWeek> tradingWeek = new List<TradingWeek>();
string End_of_Week = "Sunday";
var orderedData = FileData.OrderBy(x => x.Date)
DateTime LoopDate_Begin = new DateTime(orderedData[0].Date.Year,1,1);
int WeekCount = 1;
while (LoopDate_Begin.DayOfWeek.ToString() != End_of_Week)
{
LoopDate_Begin = LoopDate_Begin.AddDays(1);
}
foreach (var pe in orderedData)
{
do
{
if (LoopDate_Begin.DayOfYear > pe.Date.DayOfYear && LoopDate_Begin.DayOfYear < (pe.Date.DayOfYear + 7))
{
TW = new TradingWeek { Week = WeekCount, Date = pe.Date };
tradingWeek.Add(TW);
break;
}
WeekCount++;
LoopDate_Begin = LoopDate_Begin.AddDays(7);
} while (true); //need to be careful here
}
if I get you correctly, you don't need to look any further as soon as you've added your TradingWeek
So, you can
break;
after
tradingWeek.Add(TW);
You could then even leave out the
&& LoopDate_Begin.DayOfYear < (pe.Date.DayOfYear + 7)
condition since the first part is going to be true only once: for your desired interval.
You might even go for a loopless approach by dividing the number of days since your starting week by 7 - and doing some cleaning up work ;)
Can you get rid of your do loop altogether by calculating the Week Number directly? Something like the accepted answer here.
Following #nicolas78's response, something like this should work
int Year = pe.Date.Year;
DateTime Year_Begin = new DateTime(Year,1,1);
int Jan1DayOfWeek = Year_Begin.DayOfWeek;
foreach (var pe in FileData)
{
int WeekCount = (pe.Date.DayOfYear - Jan1DayOfWeek) % 7 + 1;
TradingWeek TW = new TradingWeek { Week = WeekCount, Date = pe.Date };
tradingWeek.Add(TW);
}
Depending on how DayOfWeek and DayOfYear count, that is from 0 or 1, and how your mod operation work, you may need to tweak the WeekCount computation a bit.
There's a built-in feature to get the week of the year based on the date in .NET. An example is shown below, but it may need some tweaking to fit your business scenario:
System.Globalization.CultureInfo myCI = new System.Globalization.CultureInfo("en-US");
int week = myCI.Calendar.GetWeekOfYear(DateTime.Now.ToUniversalTime(), System.Globalization.CalendarWeekRule.FirstFourDayWeek, System.DayOfWeek.Sunday);
You don't need to count at all - just do a quick calculation. This assumes that a partial week at the start of the year is week 1 and week 2 begins on the first Monday.
List<TradingWeek> tradingWeek = new List<TradingWeek>();
foreach (var pe in FileData)
{
var date = pe.Date;
while (date.DayOfWeek != DayOfWeek.Sunday)
date = date.AddDays(1);
var week = date.DayOfYear/7+1;
var TW = new TradingWeek {Week = week, Date = pe.Date};
tradingWeek.Add(TW);
}