convert 2010-04-15 23:59:59 to 15th Apr 2010 - javascript

I have the following date format: 2010-04-15 23:59:59
How would I go about converting this into: 15th Apr 2010
using javascript

Check out Datejs. You'll probably want to parse your timestamp and then call toString('MMS MMM yyyy') (or something to that effect) on it. Here's some more info on toString.
There's probably a more-lightweight solution, if this is all you're after.

Like dylanfm suggests, I would check out Datejs, but if you only want to convert the way you are describing, this might work for you:
var m = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var p = ["th","st","nd","rd"];
// create date object - have to replace dashes with slashes
var d = new Date("2010-04-15 23:59:59".replace(/-/g,"/"));
// index in array p based on date % 10
var pn = d.getDate() % 10;
// pick "th" for days 11-13
if (d.getDate() > 10 && d.getDate() < 14 ) pn = 0;
// pick "th" for days 4-9, 14-19, 24-29
if (pn >= p.length) pn = 0;
// date in format "15th Apr 2010"
var formatted = d.getDate() + p[pn] + " " + m[d.getMonth()] + " " + d.getFullYear();
Note that this is nowhere near as flexible as using a library like Datejs.

Related

Javascript datetime issue - converting to utc

My database value is this
2020-03-08 20:44:00
But in javascript. It display
Mon Mar 09 2020 09:44:00 GMT+0800 (Singapore Standard Time)
Want i want to display on UI
2020-03-08 20:44:00
or
2020-03-08
Is there a way to remove the timezone and get only the actual value from the database.
toISOString is not a proper way to get date into DateTime. please follow the below method to get a date from DateTime.
var date = new Date("2020-03-08 20:44:00");
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
var newDate = year + '-' + month + '-' + day;
console.log("Date plush time - "+date);
console.log("Only Date - "+newDate);
You're using the silently using Date object's .toString() method which converts the UTC date (that your database is storing) into a time in the current time zone.
If date is the variable that you get from your database, then you can format it like you want it like this:
let dateString = date.toISOString().replace('T', ' ').replace(/\..+/, '')
This will take your date, convert it into an ISO string (in the form 2020-01-10T03:09:24.551Z) and replace the T with a space and everything after the decimal with nothing.
Try this.
let d = new Date('2020-03-08 20:44:00');
console.log(`${d.getFullYear()}-${d.getMonth() < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1}-${d.getDate() < 10 ? '0' + (d.getDate()): d.getDate()}`);
You can take each part of the date and construct your own format
example:
let formatted_date = my_date.getFullYear() + "-" + (my_date.getMonth() + 1) + "-" + my_date.getDate()
in this example: my_date hold the date you want to display.
If you're able to use a library, use moment.js
https://momentjs.com/docs/#/displaying/
moment("2020-03-08 20:44:00").format("YYYY-MM-DD");
or
moment(new Date("2020-03-08 20:44:00")).format("YYYY-MM-DD");
It can even change the time to utc
https://momentjs.com/guides/#/parsing/local-utc-zone/
moment.utc("2020-03-08 20:44:00").format("YYYY-MM-DD");
hope this helps :)
Subtract your timezone offset milliseconds.
var dt = new Date('2020-03-08 20:44:00');
dt = new Date(dt.getTime()-dt.getTimezoneOffset()*60000);
console.log(dt.toUTCString());
var mo = dt.getUTCMonth()+1, d = dt.getUTCDate(), h = dt.getUTCHours();
var m = dt.getUTCMinutes(), s = dt.getUTCSeconds();
if(mo < 10)mo = '0'+mo;
if(d < 10)d = '0'+d;
if(h < 10)h = '0'+h;
if(m < 10)m = '0'+m;
if(s < 10)s = '0'+s;
console.log(dt.getUTCFullYear()+'-'+mo+'-'+d+' '+h+':'+m+':'+s);

Trouble converting dates string to YYYY-MM-DDTHH:MM:SS-HH:MM format

I have a start date that looks like this:
var startDate = "Mon Jun 30 2014 00:00:00 GMT-0400 (EDT)";
And I am trying to get it formatted into this:
var endDate = "2014-06-30T00:00:00-04:00";
I have gotten it to semi-format correctly using the toISOString() method:
var formattedDate = new Date(startDate);
formattedDate = formattedDate.toISOString();
Which formats it into "2014-06-30T04:00:00.000Z". This is close to what I need, but I was wondering if there was built in method to format it into the '-04:00' format? Or do I need to split my string into parts and mend it back together in the right format?
Also I am working out of Google Apps Script, which is ES5, and am trying to avoid jQuery if possible.
Google Apps Script (GAS) has a built-in utility method you can leverage to format dates:
Utilities.formatDate()
Its based on Java's SimpleDateFormat class.
To format the date to meet your requirements the following should suffice:
var date = new Date("Mon Jun 30 2014 00:00:00 GMT-0400 (EDT)");
var formattedDate = Utilities.formatDate(
date,
Session.getScriptTimeZone(),
"yyyy-MM-dd'T'HH:mm:ssXXX"
);
Note: You may need to set your script's timezone from the GAS GUI menu via:
File->Project Properties->Info
I completely agree with #JordanRunning 's comment.
Still, out of curiosity I quickly put together a way to get your desired format:
// two helper functions
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
function getOffset(offset) {
if(offset<0) {
wminutes = 0 - offset;
var posneg = "-";
} else {
wminutes = offset;
var posneg = "+";
}
var hours = pad(Math.floor(wminutes/60));
var minutes = pad(wminutes % 60);
return posneg+hours+":"+minutes;
}
// the actual format function
Date.prototype.toMyFormat = function() {
var format = this.getUTCFullYear() +
'-' + pad(this.getMonth() + 1) +
'-' + pad(this.getDate()) +
'T' + pad(this.getHours()) +
':' + pad(this.getMinutes()) +
':' + pad(this.getSeconds());
timezoneOffset = getOffset(this.getTimezoneOffset());
format += timezoneOffset;
return format;
}
// usage:
console.log(new Date().toISOString());
// "2018-11-16T20:53:11.365Z"
console.log(new Date().toMyFormat());
// "2018-11-16T21:53:11-01:00"
You can just reformat the string. The format in the OP is consistent with the format specified for Date.prototype.toString in ECMAScript 2018, so you can even reformat that wiht the same function:
// Convert string in DDD MMM DD YYYY HH:mm:ss ZZ format to
// YYYY-MM-DDTHH:mm:ssZZ format
function formatDateString(s) {
var m = {Jan:'01',Feb:'02',Mar:'03',Apr:'04',May:'05',Jun:'06',
Jul:'07',Aug:'08',Sep:'09',Oct:'10',Nov:'11',Dec:'12'};
var b = s.split(' ');
return `${b[3]}-${m[b[1]]}-${b[2]}T${b[4]}${b[5].slice(-5,-2)}:${b[5].slice(-2)}`;
}
console.log(formatDateString("Mon Jun 30 2014 00:00:00 GMT-0400 (EDT)"));
// Not recommended, but it will format any date where its
// toString method is consistent with ECMAScript 2018
console.log(formatDateString(new Date().toString()));

Javascript convert string to date format yyyy-MM-dd

I have a string which is in the format "05-01-2016" when i run the below code in chrome i get the correct output
var fromDate = new Date(searchOpts.RunDateFrom);
fromDate.format("yyyy-MM-dd");
output = "2016/05/01"
However, when this code is execute inside my js file i get this output
Sun May 01 2016 00:00:00 GMT+0530 (India Standard Time)
How do i prevent this? I need to pass the date in this format "2016-05-01" to solr
formattedDate = fromDate.getFullYear() + "-" + (fromDate.getMonth()+1) + "-" + fromDate.getDate()
If you just need the string
var year = fromDate.getFullYear();
var month = fromDate.getMonth() < 10 ? '0'+ fromDate.getMonth()+1 : fromDate.getMonth()+1
var date = fromDate.getDate() < 10 ? '0'+ fromDate.getDate(): fromDate.getDate()

Javascript convert mm/dd/yyyy hh:mm(AM|PM) to valid date object

I am trying to convert a string representing a date such as "07/13/2015 12:00AM" to a valid date object in javascript. Calling new Date("07/13/2015 12:00AM") yields an Invalid Date.
Any help is appreciated.
It seems that the date parser doesn't like having the AM/PM directly against the minutes/seconds.
Just a quick fix
var date = "07/13/2015 12:00AM";
date = date.substr(0, date.length-2) +' '+ date.substr(-2);
new Date(date);
This is a function that would turn your datetime strings to 24-Hrs format, and now it can be handled by Date()
function set24Hrs(d){
if (d.slice(-2) === "PM"){
var hrs = parseInt(d.slice(-7,-5))
var mins = d.slice(-4,-2)
hrs = hrs + 12
var dd = d.slice(0,9) + " " + hrs + ":" + mins;
return dd;
} else if(d.slice(-2) === "AM"){
return (d.slice(0, 16));
} else {
throw ("UNRECOGNIZED_FORMAT","set24Hrs() Received Unrecognized Formatted String");
}
}
So, you can just use like that:
c = new Date(set24Hrs(03/1/2015 3:00PM))
// returns: Sun Mar 01 2015 15:00:00 GMT+0200 (Egypt Standard Time)
Now you have a working solution, however if you have a lot of code to work with dates in Javascript, I recommend to take a look at libraries like date.js And moement.js
You could strip the date and rebuild like:
var timeStr = "07/13/2015 12:00AM";
var dateFormat = /(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})([AP]M)/;
var dateArray = dateFormat.exec(timeStr);
var d = new Date(dateArray[3],parseInt(dateArray[1])-1,dateArray[2],parseInt(dateArray[4])-(dateArray[6] == 'AM' ? 12 : 0),dateArray[5]);
alert(d);

Convert input type text into date format

I have one input type text:
<input type="text" id="policyholder-dob" name="policyholder-dob" />
I want to type number in this field in mm/dd/yyyy format:
like 01/01/2014
This is my js code but its not working, what mistake have I made?
function dateFormatter(date) {
var formattedDate = date.getDate()
+ '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
return formattedDate;
}
var nextduedate = $("#policyholder-dob").val();
var dateFormatDate = nextduedate.slice(0, 2);
var dateFormatMonth = nextduedate.slice(2, 4);
var dateFormatYear = nextduedate.slice(4, 8);
var totalFormat = dateFormatMonth + '/' + dateFormatDate + '/' + dateFormatYear;
var againNewDate = new Date(totalFormat);
againNewDate.setDate(againNewDate.getDate() + 1);
var todaydate = dateFormatter(againNewDate);
$("#policyholder-dob").prop("value", todaydate);
Any help will be really appreciated.
Thankfully, your input is consistently in this format:
mm/dd/yyyy
So you can convert it to a Date object through a custom function, such as:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2],
temp = [];
temp.push(y,m,d);
return (new Date(temp.join("-"))).toUTCString();
}
Or:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2];
return (new Date(y + "-" + m + "-" + d)).toUTCString();
}
Etc..
Calling it is easy:
stringToDate("12/27/1963");
And it will return the correct timestamp in GMT (so that your local timezone won't affect the date (EST -5, causing it to be 26th)):
Fri, 27 Dec 1963 00:00:00 GMT //Late december
Example
There are various ways to accomplish this, this is one of them.
I'd suggest moment.js for date manipulation. You're going to run into a world of hurt if you're trying to add 1 to month. What happens when the month is December and you end up with 13 as your month. Let a library handle all of that headache for you. And you can create your moment date with the string that you pull from the val. You substrings or parsing.
var d = moment('01/31/2014'); // creates a date of Jan 31st, 2014
var duration = moment.duration({'days' : 1}); // creates a duration object for 1 day
d.add(duration); // add duration to date
alert(d.format('MM/DD/YYYY')); // alerts 02/01/2014
Here's a fiddle showing it off.

Categories

Resources