How to convert a date to long date? - javascript

How to convert a date(01-02-2019) to Wed, 02 Jan 2019 in javascript?
$(document).ready(function () {
var dealDate = 01-02-2019;
});

Just use new Date() on that date value:
$(document).ready(function() {
var dealDate = '01-02-2019';
//replace all - to / to make it work on firefox
dealDate = dealDate.replace(/-/g,'/');
alert(new Date(dealDate).toDateString())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You can use Date Constructor and Date.prototype.toDateString():
The toDateString() method returns the date portion of a Date object in human readable form in American English.
$(document).ready(function () {
var dealDate = new Date('01-02-2019').toDateString();
console.log(dealDate);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You can split your string on - and then generate the date using Date constructor.
var dealDate = '01-02-2019';
let [month, day, year] = dealDate.split('-').map(Number);
let date = new Date(year, month - 1, day);
console.log(date.toDateString());

TO convert the date to in the format of month day, month day number and year use the below jquery. It will convert the current date to the exact format you asked for
$(document).ready(function() {
var dealDate = new Date();
alert(dealDate.toUTCString());
});

your expected format is like [day][comma][date][month][year]. I split toDateString() and rearranged in expected format.
function formatedDate(d){
var dt=new Date(d).toDateString().split(' ');
return dt[0]+', '+dt[2]+' '+dt[1]+' '+dt[3]; //[Day][comma][date][month][year]
}
console.log(formatedDate('01-02-2019'))

Related

JavaScript invalid date from DateTime Picker

I have a function that will create two dates using the result of an input with Bootstrap DateTime Picker and I need to compare both of them.
But my first value (rtime) always gives an invalid date. Where am I wrong?
Note: stime is not editable, the user only uses the DateTime Picker for rtime field.
var stime = '28/11/2017 09:18:52';
var rtime = '04/12/2017 10:16:34';
var lastReturn = new Date(rtime);
var lastOut = new Date(stime);
if (lastReturn >= lastOut) {
console.log("This date is after than the other!");
}
console.log(rtime);
console.log(stime);
console.log(lastReturn);
console.log(lastOut);
This result shows that LastOut is an invalid date:
The format must be month/day/year, not day/month/year
That why you get invallid date on 28/11/2017 09:18:52 because there isn't a 28th month.
console.log(new Date('28/11/2017 09:18:52'))
console.log(new Date('11/28/2017 09:18:52'))
The dates you're picking are probably Month/Day/Year. But your expected date is Day/Month/Year. For example, the date 04/12/2017 is returning April 12th instead of December 4th. You can use a regex on your string to replace and make it in the correct format.
Please check this snippet:
var stime = "28/11/2017 09:18:52" //$("#movesend").val();
var rtime = "04/12/2017 10:16:34" //$("#moveretorna").val();
function parseDate(dateString) {
return dateString.replace( /(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
}
var lastReturn= new Date(parseDate(rtime));
var lastOut= new Date(parseDate(stime));
if(lastReturn>= lastOut)
{
console.log("This date is after than the other!");
}
console.log(stime);
console.log(rtime);
console.log(lastReturn);
console.log(lastOut);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to convert your date from DD/MM/YYYY HH:MM:SS format to MM/DD/YYYY HH:MM:SS format.
For conversion, you can use string#replace.
var stime = '28/11/2017 09:18:52';
var rtime = '04/12/2017 10:16:34';
stime = stime.replace(/(..)\/(..)\/(.*)/, '$2/$1/$3');
rtime = rtime.replace(/(..)\/(..)\/(.*)/, '$2/$1/$3');
var lastReturn = new Date(rtime);
var lastOut = new Date(stime);
if (lastReturn >= lastOut) {
console.log("This date is after than the other!");
}
console.log(rtime);
console.log(stime);
console.log(lastReturn);
console.log(lastOut);

Datetime diff in minutes

I have 2 DateTime field in a form, and I want the difference between these 2 fields in minute.
I tried to parse DateTime into Date but it's not working :
<script>
$(document).ready(function () {
$("#mybundle_evenement_button").click(function () {
var field1 = $("#mybundle_evenement_debut").val();
var field2 = $("#mybundle_evenement_fin").val();
var date1 = new Date(field1);
var date2 = new Date(field2);
alert(date1);
});
});
</script>
If I alert() date1, it shows Invalid Date.
But if I alert() field1, it shows 15/09/2017 13:32 (format is : days/months/year hour:minutes).
Is it possible that new Date(field1) isn't working because of the format ?
I know that if I succeed to parse DateTime into Date, it'll be easy to have the difference in minutes, but I don't understand why it says Invalid Date.
dd/MM/yyyy HH:mm isn't a valid date format for Date.parse()
You have to format your date to a valid Date Time String Format, for example:
var field1 = $("#mybundle_evenement_debut").val();
var ISODate1 = field1.replace(/(\d+)\/(\d+)\/(\d+)/, "$3-$2-$1")
var date1 = new Date(ISODate1);
alert(date1) // => Fri Sep 15 2017 13:32:00 ...
The problem is about the format you are getting the date from the field. new Date() don't accepts this format. I think the best is to parse the string yourself. If the format is always the same just use new Date(year, month, day, hours, minutes, seconds, milliseconds).
var day = field.splice(0,2); field.splice(0,1);
var month = field.splice(0,2); field.splice(0,1);
var year = field.splice(0,2); field.splice(0,1);
var hour = field.splice(0,2); field.splice(0,1);
var minute = field.splice(0,2);
It's depend on your browser. I'll suggest to use the standard format is '2013/12/09 10:00'.
Okay! come to the point. You need to manually format the date from my latest answer regarding this same kind of issue. Please take a look at this link : Stange javascript Date behaviour on particular dates
And you could try this below code for getting the date difference in minutes.
var startTime = new Date('2013/12/09 10:00');
var endTime = new Date('2014/12/09 10:00');
var difference = endTime.getTime() - startTime.getTime();
var result = Math.round(difference / 60000);
alert(result);

Parse string in given format to date

I want to parse date in the format ddMMyyhhmm (eg 2804121530 representing 28th April 2012, 3:30 PM) to javascript Date() object.
Is there any oneliner solution to it? I'm looking for something of the kind:
var date = Date.parse('2804121530', 'ddMMyyhhmm');
or
var date = new Date('2804121530', 'ddMMyyhhmm');
Thanks for help!
A useful library here is DateJs. Just add a reference:
<script src="http://datejs.googlecode.com/files/date.js"
type="text/javascript"></script>
and use Date.parseExact:
var dateStr = '2804121530';
var date = Date.parseExact(dateStr, 'ddMMyyHHmm');
For a fast solution you can brake that string into pieces and create date from those pieces
function myDateFormat(myDate){
var day = myDate[0]+''+myDate[1];
var month = parseInt(myDate[2]+''+myDate[3], 10) - 1;
var year = '20'+myDate[4]+''+myDate[5];
var hour = myDate[6]+''+myDate[7];
var minute = myDate[8]+''+myDate[9];
return new Date(year,month,day,hour,minute,0,0);
}
var myDate = myDateFormat('2804121530');
or a simper solution:
function myDateFormat(myDate){
return new Date(('20'+myDate.slice(4,6)),(parseInt(myDate.slice(2,4), 10)-1),myDate.slice(0,2),myDate.slice(6,8),myDate.slice(8,10),0,0);
}
var myDate = myDateFormat('2804121530');
(new Date(1381344723000)).toUTCString()
Correct me if 'm worng...

Convert dd-mm-yyyy string to date

i am trying to convert a string in the format dd-mm-yyyy into a date object in JavaScript using the following:
var from = $("#datepicker").val();
var to = $("#datepickertwo").val();
var f = new Date(from);
var t = new Date(to);
("#datepicker").val() contains a date in the format dd-mm-yyyy.
When I do the following, I get "Invalid Date":
alert(f);
Is this because of the '-' symbol? How can I overcome this?
Split on "-"
Parse the string into the parts you need:
var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])
Use regex
var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"))
Why not use regex?
Because you know you'll be working on a string made up of three parts, separated by hyphens.
However, if you were looking for that same string within another string, regex would be the way to go.
Reuse
Because you're doing this more than once in your sample code, and maybe elsewhere in your code base, wrap it up in a function:
function toDate(dateStr) {
var parts = dateStr.split("-")
return new Date(parts[2], parts[1] - 1, parts[0])
}
Using as:
var from = $("#datepicker").val()
var to = $("#datepickertwo").val()
var f = toDate(from)
var t = toDate(to)
Or if you don't mind jQuery in your function:
function toDate(selector) {
var from = $(selector).val().split("-")
return new Date(from[2], from[1] - 1, from[0])
}
Using as:
var f = toDate("#datepicker")
var t = toDate("#datepickertwo")
Modern JavaScript
If you're able to use more modern JS, array destructuring is a nice touch also:
const toDate = (dateStr) => {
const [day, month, year] = dateStr.split("-")
return new Date(year, month - 1, day)
}
regular expression example:
new Date( "13-01-2011".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3") );
Another possibility:
var from = "10-11-2011";
var numbers = from.match(/\d+/g);
var date = new Date(numbers[2], numbers[0]-1, numbers[1]);
Match the digits and reorder them
Using moment.js example:
var from = '11-04-2017' // OR $("#datepicker").val();
var milliseconds = moment(from, "DD-MM-YYYY").format('x');
var f = new Date(milliseconds)
Use this format: myDate = new Date('2011-01-03'); // Mon Jan 03 2011 00:00:00
var from = $("#datepicker").val();
var f = $.datepicker.parseDate("d-m-Y", from);
You can also write a date inside the parentheses of the Date() object, like these:
new Date("Month dd, yyyy hh:mm:ss")
new Date("Month dd, yyyy")
new Date(yyyy,mm,dd,hh,mm,ss)
new Date(yyyy,mm,dd)
new Date(milliseconds)
In my case
new Date("20151102034013".replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, "$1-$2-$3T$4:$5:$6"))
Result: Mon Nov 02 2015 04:40:13 GMT+0100 (CET)
then I use .getTime() to work with milliseconds
The accepted answer kinda has a bug
var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])
Consider if the datepicker contains "77-78-7980" which is obviously not a valid date. This would result in:
var f = new Date(7980, 77, 77);
=> Date 7986-08-15T22:00:00.000Z
Which is probably not the desired result.
The reason for this is explained on the MDN site:
Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1).
A better way to solve the problem is:
const stringToDate = function(dateString) {
const [dd, mm, yyyy] = dateString.split("-");
return new Date(`${yyyy}-${mm}-${dd}`);
};
console.log(stringToDate('04-04-2019'));
// Date 2019-04-04T00:00:00.000Z
console.log(stringToDate('77-78-7980'));
// Invalid Date
This gives you the possibility to handle invalid input.
For example:
const date = stringToDate("77-78-7980");
if (date === "Invalid Date" || isNaN(date)) {
console.log("It's all gone bad");
} else {
// Do something with your valid date here
}
You can use an external library to help you out.
http://www.mattkruse.com/javascript/date/source.html
getDateFromFormat(val,format);
Also see this: Parse DateTime string in JavaScript
You can just:
var f = new Date(from.split('-').reverse().join('/'));
let dateString = '13-02-2021' //date string in dd-mm-yyyy format
let dateArray = dateString.split("-");
//dateArray[2] equals to 2021
//dateArray[1] equals to 02
//dateArray[0] equals to 13
// using template literals below
let dateObj = new Date(`${dateArray[2]}-${dateArray[1]}-${dateArray[0]}`);
// dateObj equals to Sat Feb 13 2021 05:30:00 GMT+0530 (India Standard Time)
//I'm from India so its showing GMT+0530
P.S : Always refer docs for basics, MDN or DevDocs
Take a look at Datejs for all those petty date related issues.. You could solve this by parseDate function too
You could use a Regexp.
var result = /^(\d{2})-(\d{2})-(\d{4})$/.exec($("#datepicker").val());
if (result) {
from = new Date(
parseInt(result[3], 10),
parseInt(result[2], 10) - 1,
parseInt(result[1], 10)
);
}
new Date().toLocaleDateString();
simple as that, just pass your date to js Date Object

Convert yyyy-mm-dd to UTC in Javascript

I need to convert a date in yyyy-mm-dd like 2011-12-30 to UTC using only javascript. How?
var utc = new Date('2011-12-30').toUTCString();
jsFiddle.
If you're having problems getting the other listed solution to work in firefox or safari you can use: http://www.datejs.com/
myDate = new Date.parse("2011-12-30")
myUTCDate = Date.UTC(myDate.getFullYear(), myDate.getMonth(), myDate.getDate(), myDate.getHours(), myDate.getMinutes(), myDate.getSeconds(), myDate.getMilliseconds());
Voila!!
This is very simple method to convert String to Date in JavaScript
var msomtDate = Date.parse('Here Your Date String'+' UTC',"yyyy/MM/dd HH:mm:ss");
var toUTC = function (date) {
var newDate = new Date();
newDate.setTime(date.getTime() + (date.getTimezoneOffset() * 60 * 1000));
return newDate;
};
console.log(toUTC(new Date('2011-12-30')));

Categories