How can I create a formatted date field in javascript - javascript

In Javascript I want to be able to create a string for a date. I would like to use the format
dd-MMM-yyyy
I would like the dd part to change between 1 and 29 every time I create the variable (I'm using a loop)
the MMM is set to Jan
the yyyy to 1999
Can someone help by giving me advice on how I can do this?

var formatted_date = Math.floor(Math.random() * 29) + 1 + '-Jan-1999';
console.log(formatted_date);

You can do several things.
Check out 10 ways to format date and time using Javascript.
Another set of examples here.

Related

YYYY-MM-DDTHH:mm not getting am/pm momentjs

I know this type of question is not really apropiated, but I'm stuck on it and some help would be apreciated it. I have the following date:
2018-04-26T08:19:30+02:00
But when I try to get the Hours and Minutes, the result I get is:
20:19 p
What I'm doing is the following:
let momentDay = (moment(el.time,'HH:mm a').format('HH:mm a'));
I don't know how I could get the real time, the one should give me: 08:19 instead of 20:19
Thanks
You should use hh for twelve hour time, rather than HH, which is for 24 hour time.
Also, if el.time is a datetime object, or a recognizable unambiguous date format (as yours is), then you don't need to specify a format in the constructor:
let momentDay = moment(el.time).format('hh:mm aa');

How to get hours in moment.js in GMT timezone?

For example if I do for the above date object something like: value.hours(), I get as output 16 instead of 18. I believe it returns the hours in the original GMT time, not like in my date object which is GMT+2. I can of course add 2 to the returned result, but it becomes cumbersome. Is there any way to get the hours correctly in my case?
I'm not sure as to what you've already tried, but I put the following into JSFiddle and it worked like a charm. I am currently in CST in America and it is 8:30 in the morning here. When I ran the snippet below I got today's date at 1:30 PM which I would assume is accurate in difference.
HTML
<div id="m1"></div>
JavaScript
var a = moment.tz(new Date(), "GMT");
document.getElementById('m1').innerHTML = a.format("YYYY MM DD; HH:mm");
The Moment.js documentation states the following in regards to creating a Moment object with a native JavaScript Date object:
You can create a Moment with a pre-existing native JavaScript Date object.
var day = new Date(2011, 9, 16);
var dayWrapper = moment(day);
This clones the Date object; further changes to the Date won't affect the Moment, and vice-versa.
To find the information quoted above quickly, when you reach the Moment.js documentation, it is located under the Parse section under sub-section Date.
To display local time:
value.local();
value.hours(); // 18
To reverse:
value.utc();
value.hours(); // 16
I think that you can solve it by doing what the docs says. Something like this:
moment().tz("America/Los_Angeles").format();
https://momentjs.com/timezone/docs/#/using-timezones/

A Past Numeric Date without Time

I've been searching and I can't find a solution for this.
I need javascript code that displays the date in the mm/dd/yyyy without displaying the time, but I need it to be a past date. Like for instance 61 days prior to today's date. Whatever the date is, it will display the date 61 days ago.
You could use the moment library
And do:
moment().subtract('days', 61).calendar()
Would this work for you: var PastDate = new Date(pastyear, pastmonth, pastday);
Check here for more details: Date-Javascript
Then if you wanted to get a string with just the Date and no time use something like this:
var stringDate = ++PastDate.GetMonth() + "/" + PastDate.GetDate() +"/" + PastDate.GetFullYear();

Getting next day date for specific string format in Google Apps Script (JavaScript)

Good day everyone!
Working on aprojectmI had to start working with Google Spereadsheet interface and faced a problem I cannot quickly overcome due to not working with JavaScripts ever before.
I have a date in specific format as a string
var date = "2012-08-09";
What I need is to get the next day date as
date = "2012-08-10";
which should include changing not only the day, but month and year too, if necessary.
I've tried using date format
var datum= new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.toString('yyyy-MM-dd');
but the code appears to fail at writing date to datum variable.
What is the best and quickiest way tosolve this litle problem?
Thanks
The problem when you tag a question 'Javascript' and when you are actually using Google Apps Script is that you get nice answers from people that do not know some special functions available in GAS.
GAS is based on Javascript but Javascript is not GAS... if you see what I mean ;-)
That said, there is actually a "special" function to format date string and I'll show it in the following code.
But there is also another point that could put you into trouble : if you don't mention hours in your date object there is a risk to shift one day if you live in a country that uses daylight savings. This issue has been discussed quite often on this forum and elsewhere so I won't give all the details but it's a good idea to take this into account when you play with date objects. In the code below I extract a tz (time zone) string from the date object we have just created to know if it's in summer or in winter time, then I use this tz string as a parameter in the Utilities.formatDate() method . This guarantees an exact result in every situations.
Here is (finally) the test code :
(use the logger to see results. script editor>view>logs)
function test(){
date = "2012-08-9";
var parts = date.split('-')
var datum = new Date(parts[0],parts[1]-1,parts[2],0,0,0,0);// set hours, min, sec & milliSec to 0
var tz = new Date(datum).toString().substr(25,8);// get the tz string
Logger.log(datum+' in TimeZone '+tz)
datum.setDate(datum.getDate() + 1);// add 1 day
var dateString = Utilities.formatDate(datum,tz,'yyyy-MMM-dd');// show result like you want, see doc for details
Logger.log(dateString);// the day after !
}
Logger results :
Thu Aug 09 2012 00:00:00 GMT+0200 (CEST) in TimeZone GMT+0200
2012-Aug-10
It sounds like a parsing problem you may have better luck, splitting out the date and putting the parameters in individually, any errors you get would be useful:-
var parts = date.split("-");
var datum = new Date(
parseInt(parts[0], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[2], 10));
There is no built in formatting function for the JavaScript Date object, I'm not sure if the google apps api is any different though. To perform the last line of your code you may either need to write your own functions to extract the data from the JavaScript date object and format it, hint you will also need to write a zerofill function if you want to ensure two digits in your date and month parts of the output.
var formatted = datum.getFullYear() + "-" +
zerofill(datum.getMonth() + 1, 2) + "-" +
zerofill(datum.getDate(), 2);
Passing a format string to toString works in .NET, and it may work in Java, however this doesn't work in Javascript.
Try the following,
var date = "2012-08-09";
var datum = new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.getFullYear() + "-" + (datum.getMonth() + 1) + "-" + datum.getDate();
Try the following in http://jsfiddle.net/ It works.....
<html>
<head>
<script>
function foo(){
var date = "2012-08-09";
var datum = new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.getFullYear() + "-" + (datum.getMonth() + 1) + "-" + datum.getDate();
document.getElementById("demo").innerHTML = date;
}
</script>
</head>
<body onload="foo()">
<p id=demo></p>
</body>
</html>​

How to get difference of saved time and current time in jquery?

I want to get the time difference between saved time and current time in javascript or jquery. My saved time looks like Sun Oct 24 15:55:56 GMT+05:30 2010.
The date format code in java looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
How to compare it with the current time and get the difference?
Is there any inbuilt function in jquery or javascript??
Any suggestions or links would be appreciative!!!
Thanks in Advance!
Update
Date is stored as varchar in the DB. I am retriving it to a String variable and then change it to java.util.Date object. The java code looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
This date object was sent to client. There i want to compare the saved date with current date and want to show the time difference like 2 secs ago, 2 hours ago, 2 days ago etc... like exactly in facebook. I have gone through some date to timestamp conversion tutorial in java script and now i can get the difference in timestamp. Now, i want to know how i shall change it to some format like "2 secs or 2 days or 24 hours"??. Or, how i shall change it back to date format???
Convert them into timestamps which are actually integers and can get subtracted from each other. The you just have to convert back the resulting timestamp to a javascript date object.
var diff = new Date();
diff.setTime( time2.getTime()-time1.getTime() );
You dont need to explicit convert, just do this:
var timediff = new Date() - savedTime;
This will return the difference in milliseconds.
jQuery doesn't add anything for working with dates. I'd recommend using Datejs in the event that the standard JavaScript Date API isn't sufficient.
Perhaps you could clarify exactly what input and output you're aiming for. What do you mean by "the difference?" There is more than one way to express the difference between to instants in time (primarily units and output string formatting).
Edit: since you said you're working with jQuery, how about using CuteTime? (Demo page)

Categories

Resources