How to format datestring to d, MMM yyyy in javascript - javascript

I got this:
function parseDate(s)
{
var d = s.split(/\D/);
return new Date(d[2], --d[1], d[0]);
with the calendar tag like this:
<p:calendar
id="testDate"
styleClass="calendar"
pattern="d MMM, yyyy"
maxlength="10"
onchange="$(this).val(parseDate($(this).val()))"
onfocus="$(this).mask('99/99/9999');"
>
<p:watermark for="testDate" value="mm/dd/yyyy" />
</p:calendar>
I need to manually parse a date from 'dd/mm/yyyy' to 'd, MMM yyyy' but with the function above the result is e.g. "Wed, Aug 09 1995 00:00:00" hence could someone help me and tell how how i could change the format so that the string produced would be d, MMM yyyy?
I know this should be a very basic task however i am still learning how to code better, therefore all your help and explanations are greatly appreciated!

Take a look at momentjs you can use it to parse your date and format it into whatever format you'd like.

Lazy method: use the .toString()
function parseMyDate(s){
var dateParts = s.split("/");
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
var dateStrParts = date.toString().split(" ");
return (date.getDate() + ", " + dateStrParts[1] + " " + dateStrParts[3]);
}
console.log(parseMyDate("09/06/2014"));
JSFiddle Demo

Related

Javascript - Add comma between date and time format

I'm trying to add a string comma (,) between the date and time formats. Can someone kindly show how I can achieve this for the following code? I thought it might be as simple as adding a comma in between, but unfortunately this doesn't seem to be working for me.
Example:
14 JUN 21, 18:55:03
Line 1:
return handleFileType(req, res, user, dataFile, email, origin, previewSubject, finalFormatDate.format('DD MMM YY HH:mm:ss')
Line 2:
const date = moment.unix(dateToUnixTimestamp(memo.createdAt)).format('DD MMM YY HH:mm:ss');
The reason I published both these lines, is because I'm not sure if anything can vary between them.
The format method parses a format string and replaces tokens with values from the date. Non–tokens are kept as–is, so just add the comma where you want it in the format string:
format('DD MMM YY, HH:mm:ss')
let date1 = moment().format('DD MMM YY HH:mm:ss');
console.log(date1)
let date2 = moment().format('DD MMM YY, HH:mm:ss');
console.log(date2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
If you prefer to avoid using moment.js, it is also possible with native Date javascript class methods:
let a = new Date();
let timeStr = a.toLocaleTimeString('en-GB')
let dateStr = a.toLocaleDateString('en-GB')
let timeDateStr = dateStr + ', ' + timeStr;
console.log(timeDateStr);

Format date in javascript AM and PM

I have this date 20/4/2016;4:23:00;PM
But i want to put in like this DD/MM/YYYY HH:mm:ss without the AM or PM
For example 20/04/2016 16:23:00
Thanks in advance
Carlos Vieira
In javascript the supported format for in your case is "MM/DD/YYYY hh:mm:ss AM" or "MM/DD/YYYY hh:mm:ss PM".
If you will give input like "04/20/2016 11:00:06 PM" then you will get an output as date format "Fri Mar 04 2016 23:00:06 GMT+0530 (IST)" which you can save it.
You can put "04/20/2016 11:00:06Z PM" mark here and get the result according to the UTC.
For reference https://www.w3schools.com/js/js_date_formats.asp
One approach is to reformat the string and convert the time part to 24hr time, e.g:
function reformatDate(s) {
var b = s.split(';');
var t = b[1].split(':');
var h = +t[0];
h = h%12 + (/pm/i.test(b[2])? 12 : 0);
return b[0] + ' ' + h + ':' + t[1] + ':' + t[2];
}
console.log(reformatDate('20/4/2016;4:23:00;PM')); // 20/4/2016 16:23:00
That avoids the vagaries of parsing the entire string to a date then reformatting it. If that's what you want to do, there are plenty of questions here already on parsing and formatting dates:
Where can I find documentation on formatting a date in JavaScript?
lots of parsing questions

New date() returning next date instead of today's date

i am trying to convert a string into date type.i am giving the string value to new date().
but it's returning next day date instead of date which i am trying to convert.
var endDate = new Date("2017-03-23T23:59:59.000Z");
//end date value is now ------ Fri Mar 24 2017 05:29:59 GMT+0530 (India Standard Time).
Please suggest me how can get correct date in the format MM/DD/YYYY
This hack can help you,
var endDate = new Date("2017-03-23T23:59:59.000Z").toISOString();
it will give you,
"2017-03-23T23:59:59.000Z"
Further if you want to convert it to DD/MM/YYYY then you can use native javascript or lib like moment for that,
This simpile js will help to convert it to any format.
var endDate = new Date("2017-03-23T23:59:59.000Z").toISOString();
var d1 = endDate.split('T'); //spliting date from T
var d2 = d1[0].split('-'); //getting date part
console.log('yyyy/MM/dd', d2[0] + "/" + d2[1] + "/" + d2[2]) //YYYY/MM/DD
console.log("DD/MM/YYYY", d2[2] + "/" + d2[1] + "/" + d2[0])
jsfiddle link
if your time is in IST use below
var endDate = new Date("2017-03-23T23:59:59.00+0530");
If you check dates, you will see that your dates differs in 5h 30 mins, that is same as your date saying GMT +0530. Your original date has .000Z that is time zone of GMT +0.
Make sure you use same time zone when working with date.
Try using Date.UTC('your date')
JavaScript Date objects carry no timezone information. The only reason you saw a non-UTC date is that the browser chooses by default to display dates as local time in the console. If you don't care about the date object aligning with the exact instant in local time, you can use the following format function to turn it into MM/DD/YYYY format:
function format (date) {
var mm = ('0' + (date.getUTCMonth() + 1)).slice(-2)
var dd = ('0' + date.getUTCDate()).slice(-2)
var yyyy = date.getUTCFullYear()
return mm + '/' + dd + '/' + yyyy
}
var endDate = new Date("2017-03-23T23:59:59.000Z")
console.log(endDate.toISOString())
console.log(format(endDate))
(Credit to Ranj for posting an answer using Date#toISOString before mine.)
I have created the solution over here please find below link
https://www.w3schools.com/code/tryit.asp?filename=FD0YSGRMB59W

Javascript string to date

I have this string in Javascript
"/Date(1317772800000)/"
and I'd like to display it as a meaningful date in my page. Currently, when I output the variable that contains this date I get the following displayed on my page
/Date(1317772800000)/
What I'd like is to display this in the format DD MM YYYY like so
10 05 2011
How is this possible?
try this
var date = new Date(Number.parseFloat('/Date(1317772800000)/'.substring(6)));
var newdate = date.getMonth() +' ' +date.getDate() +' ' +date.getFullYear()
If you have your date in a string provided then first you need to extract the number:
var strDate = "/Date(1317772800000)/";
var dateInt = strDate.replace("/Date(","").replace(")/","");
var date = new Date(parseInt(dateInt))
This gives you a JavaScript date object that you can do pretty much a lot with, if you want simple check just execute:
alert(date)
Try using moment.js i.e.:
moment().format('MMMM Do YYYY, h:mm:ss a')
Then you can do:
moment(1317772800000).format("MMM Do YY");
Try this
unixtime = 1317772800000;
var newDate = new Date();
newDate.setTime(unixtime);
dateString = newDate.toUTCString();
alert(dateString);
DEMO

Creating a Javascript Date object by passing in a date? What is a dateString?

I am trying to figure out what the W3C website means by dateString.
http://www.w3schools.com/jsref/jsref_obj_date.asp
I am trying to do something like:
var _date = new Date("Mon Aug 12 2013 2:00 AM");
or even:
var _date = new Date("Mon, Aug 12 2013, 2:00 AM");
Is there a quick way of turning my string into a format that the date object likes?
Thank you
edit:
I suppose it expects the following:
var d = new Date()
d.toDateString()
"Tue Aug 13 2013"
Is it only that type of string?
The Javascript string-based Date constructor accepts strings in a format accepted by Date.parse().
These are date strings compliant with RFC-2822 or ISO-8601.
Use String in this format:
new Date('2013-08-13')
or
new Date('2013-08-13T10:51:00');
Here, this is how to use dateString as a parameter
var dateString = "08/12/2013";
var d = new Date(dateString);
dateString = d.getFullYear() + "/" + d.getMonth() + "/" + d.getDate();
document.write(dateString);
Remember month are stored at 0th index in javascript.

Categories

Resources