How to use moment js for displaying formatted date? - javascript

Guys I am getting date through ajax call in my ASP.net mvc application. Now the date I am getting is in the format of 2014-06-09T17:38:55 however I want to display it in three formats:
Like this 06/09/2014 05:38:55 PM
Like three hours ago or Yesterday style (used by facebook)
Just the date part like 06/09/2014
Basically I have a hidden input field in my view which gets the Date from ajax call. Now I am doing something like this :
<input id="hiddenLastAlertDate" type="hidden" value="values.CreationDate" />
In my script section, I have a function in which I am doing something like this:
var datefield = document.getElementById("hiddenLastAlertDate").value;
formattedDate = moment(datefield).format('L'); //for getting the date part only
Upon running the application,formattedDate shows up as undefined. Why is that? I think I was unable to follow the moment.js documentation. How can I use moment.js to get this formatted result ?

moment("20140618 08:00", "YYYYMMDD hh:mm").fromNow(); will return 2 hours ago
moment("20140617", "YYYYMMDD").fromNow(); will return a day ago
moment().format('DD/MM/YYYY h:mm:ss A'); will return 18/06/2014 9:42:24 AM

Related

Get date inside jquery datepicker with not-ISO date format

I'm using jQuery datepicker to set the limit in a time series made with Highcharts for a personal project.
My date format is dd/mm/yyyy.
Following code works for sure till some weeks ago
onSelect: function () {
var minTime = $('input.highcharts-range-selector:eq(0)').datepicker("getDate").getTime();
var maxTime = $('input.highcharts-range-selector:eq(1)').datepicker("getDate").getTime();
}
But now I get following error:
"The specified value "03/02/2021" does not conform to the required format, "yyyy-MM-dd".
Searching I've understood that it depends on the fact that I'm using a format different from the ISO.
How I can fix this issue maintaining my date format?
Bonus question:
What could be changed from the last time that I've checked my site?
Thank you all

ionic 2 ion-datetime ISO Format issue

I am using ion-datetime for my appointment form. While inserting it is working fine without any problem. But when I need to update the inserted appointment date form details from back end, the date value is not displaying in ion-datetime.
Below is my code:
update.html:
<ion-item class="border-bottom">
<ion-label class="ionselect" >Appointment Date:</ion-label>
<ion-datetime name="appdate" displayFormat="YYYY MMM DD" [(ngModel)]="leadDetailsUpdate.appt_date"></ion-datetime>
</ion-item>
update.ts:
leadDetailsUpdate={
appt_date:''
};
The Date format I am getting from back end as follows:
appt_date: "2017-01-01"
Below is the error message I am getting in console:
Error parsing date: "null". Please provide a valid ISO 8601 datetime format: https://www.w3.org/TR/NOTE-datetime
convert it to ISO format before displaying
var date = new Date('2017-01-01').toISOString()
console.log(date)
Even Gaurav is right, I found that if your timezone is not +0, you can have problems with that. I found somewhere this solution:
let tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
this.startTime = (new Date(this.myStartTime - tzoffset)).toISOString().slice(0,-1);
Then in my HTML I have it like this:
<ion-datetime displayFormat="HH:mm" [(ngModel)]="startTime" (ionChange)="changeCheckOutStartTime()" style="padding-left: 21px"></ion-datetime>
And in the changeCheckOutStartTime() method, I take the time and create a moment:
changeCheckOutStartTime() {
this.myStartTime = moment(this.startTime).toDate();
}
Using ISO format before displaying, like this:
this.myDate = new Date('2017-01-01').toISOString()
Will give us a difference of hours, each browser would do something different. In my case I had a difference of 5 hours (16/12/17 02:00 would be 16/12/17 07:00).
A better way would be to use moment as ionic recomends on its documentationn (https://ionicframework.com/docs/api/components/datetime/DateTime/#advanced-datetime-validation-and-manipulation)
Example:
Open console at root proyect and install moment: npm install moment --S.
Import moment in component file: import moment from 'moment';.
Set value of model variable: this.myDate = moment().format().
The best would be create a pipe. Well check this demo http://plnkr.co/edit/MHjUdC for inspiration, goog luck :)

Angularjs date display

Hi I am trying to figure out how to display date properly using angularjs.
My system returns the date in this fromat
c_date="\/Date(1151470800000-0500)\/"
I dont know what format is it.
I am displaying it
using <span>{{pro.c_date | date:'medium')</span>
When i run this i get date printed in same format
"/Date(1151470800000-0500)/"
Can anyone suggest how to fix this so date can be displayed properly.
Thanks
the date that you're trying to use is a invalid date or maybe I don't know what format are the system using.
The problem is that angular.js requires a data object for can format it. Not a date string.
I suppose that the date is 1151470800000 miliseconds since the epoch least 0500 for adjust hours or something.
If this is correct, you only need to make c_date a Date object before pass to view.
c_date = "\/Date(1151470800000-0500)\/";
var the_date = eval("new "+c_date.replace(/\\|\//g, ''));
http://jsbin.com/zuwizoxe/3/
Regards!

Angularjs, Datepicker one day beind

I understand that the datepicker (I'm using AngularStrap's datepicker) is "behind" a day because of how dates are calculated in javascript. My problem is, how to I get it to not take the timezone into consideration and just stick with the entered date... no adjustments?
I select February 1, 2014 in the datepicker. My value on the screen is 2/1/2014 and I want that value to be saved. However, the datepicker turns this into Fri Jan 31 2014 19:00:00 GMT-0500 (EST) apparently because it subtracts the 5 hours for my timezone from the entered date. I do not want this. If I enter 2/1/2014 I want that date, regardless of the timezone.
What is the best way to intercept/change/edit this value so that entering 2/1/2014 gives me exactly that date... no conversion for timezone? Should I modify the datepicker code itself (this seems like a bad idea)? Should I change the value myself prior to sending it to the backend by adding in some sort of offset? If so, how do you add time to a value that console displays as Fri Jan 31 2014 19:00:00 GMT-0500 (EST)?
I solved this problem with a custom directive https://gist.github.com/weberste/354a3f0a9ea58e0ea0de
It's for Angular Bootstrap datepicker but I guess it should work for AngularStrap datepicker as well since it only depends on the corresponding ngModel rather than the datepicker itself.
Essentially, I'm reformatting the value whenever a date is selected on the datepicker (this value, a yyyy-mm-dd formatted string, will be stored on the model) and whenever the model is accessed to populate the view, I need to wrap it in a Date object again so datepicker handles it properly.
In other words, it is exactly doing the interceptions that you ask for in your question.
I know this thread is kind of old but since there is no accepted solution I thought I'd offer what finally worked for me after lots of messing around:
The issue in my case was that the datepicker was using the wrong timezone so when I would try to edit an event, the wrong date would display even though the correct date was stored in the db. The following fixed it for me:
var evDate = new Date(data.eventDate); //data.eventDate is the date string
evDate.setMinutes(evDate.getMinutes() + evDate.getTimezoneOffset());
$scope.eventInfo.eventDate = evDate;
I found this solution here: https://github.com/angular-ui/bootstrap/issues/2628
If you don't mind loading another resource, then I would recommend using MomentJS as it takes the pain out of dates in JavaScript. You can do something like `moment(datepicker value).local()' to get the date without the timezone offset.
http://momentjs.com/docs/#/manipulating/local/
I have found a way. convert that date to string first. here is the code.
var SelectDate = $scope.GetFormattedDate(Date.parse($("#Date").datepicker("getDate")));
$scope.GetFormattedDate = function (CalDate) {
var re = /-?\d+/;
var WDate = CalDate.toString();
var m = re.exec(WDate);
var lastDate = new Date(parseInt(m[0]));
var mm = lastDate.getMonth() + 1;
var dd = lastDate.getDate();
var yyyy = lastDate.getFullYear();
var formattedDate = mm + '/' + dd + '/' + yyyy;
return formattedDate;
}
Now Pass SelectDate to your controller. bingo problem has been resolved :)
Guys if you are experiencing this problem is because probably,you are reactivily ,puting data in boostrap datepicker.This solution worked for me.
First you check if date is null
dateBegin===null?dateBegin=null:dateBegin = new Date(formatDate(dateBegin,'yyyy-MM-dd','en'));
**if is null you set its value to null which you are going putt in your Form Group and in Form Group Control
this.ugovorForm = new FormGroup({'dateBegin':new FormControl(dateBegin)})
else you will set Date and format it using formatDate property , provided by Angular.I was struguling with this problem for along time.And its because I'm loading dates from Database.Good Luck;

Convert a time string say '12:05 PM' into a datetime using Date.Parse in Javascript

I want to convert a time string say '12:05 PM' into a datetime using Date.Parse in Javascript.
When I pass in a value of say 12:05 PM or 12:10 PM or ... or 12:55 PM the value returned by startTime below is null, i.e. startTime = null
But when I pass in values of 1:00 PM, 1:05 PM, 1:10 PM, 12:00 AM,...,12:00 PM it works fine
returning me a Date with the time included.
This is the code line causing an issue:
var startTime = Date.parse($("#<%= StartTime.ClientID %>").val()); //code causing the issue
And StartTime is a textbox.
I am writing the above code in client/html in an ASP.NET application on the web form.
If you're using date.js then try (as per test case here)
Date.parseExact("12:05 PM", "hh:mm tt");
This should also pick up if you've loaded the library correctly.
It works fine here:
http://jsfiddle.net/vuURb/396/
It's possible that it is a library loading issue, but you claim it works on some times and not others. Have you tried outputting the value of the text box to the console before feeding it to Date.parse()?
there's a good utility for dates named date.js.
Based on this answer you can do this:
var startTime = new Date();
var time = $("#<%= StartTime.ClientID %>").val().match(/(\d+)(?::(\d\d))?\s*(p?)/);
startTime.setHours(parseInt(time[1]) + (time[3] ? 12 : 0) );
startTime.setMinutes( parseInt(time[2]) || 0 );
I just read on your reply to the other question that you are using date.js. If you really are using it, your code is correct, then the problem should be that you are not loading the library properly, and you are using the native Date object.

Categories