Parse string in given format to date - javascript

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...

Related

How to convert a date to long date?

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'))

How do I get the time in milliseconds from 2 different string?

I have the following code which I get from parameters in the URL.
This is what I have in the URL
&dateStart=15.01.2015&timeStart=08%3A00&
After getting the parameters I have the following: 15.01.2015:08:00
Using Javascript how can I parse this string to get the date in milliseconds?
Date.parse(15.01.2015:08:00)
But obviously this doesn't work.
Date.parse(15-01-2015)
This works and I can change this but then how do I add or get the milliseconds from the time??
This is quite possibly the ugliest JavaScript function I've written in my life but it should work for you.
function millisecondsFromMyDateTime(dateTime) {
var dayMonth = dateTime.split('.');
var yearHourMinute = dayMonth[2].split(':');
var year = yearHourMinute[0];
var month = parseInt(dayMonth[1]) - 1;
var day = dayMonth[0];
var hour = yearHourMinute[1];
var minute = yearHourMinute[2];
var dateTimeObj = new Date(year, month, day, hour, minute, 0, 0);
return dateTimeObj.getTime();
}
It will work with the format that your DateTime is in aka day.month.year:hours:minutes.
You can achieve it using Javascript Date Object and JavaScript getTime() Method:
var dateString="01.15.2015 08:00";
var d = new Date(dateString);
console.log(d);
var ms=d.getTime();
console.log(ms);
ms+=10000;
console.log(new Date(ms));
Here is a DEMO Fiddle.
Note: Change your date string from 15.01.2015:08:00 to "01.15.2015 08:00" because it's not a valid Date format.
Check for format
Date() in javascript :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Format allowed :
https://www.rfc-editor.org/rfc/rfc2822#page-14
You can try to use moment.js library like this:
moment('15.01.2015 08:00', 'DD.MM.YYYY HH:mm').milliseconds()
Just for the sake of completion, you can always extract the information and create a Date object from the extracted data.
var dateStart = '15.01.2015'
var timeStart = '08:00';
var year = dateStart.substring(6,10);
var month = dateStart.substring(3,5);
var day = dateStart.substring(0,2);
var hour = timeStart.substring(0,2);
var mins = timeStart.substring(3,5);
var fulldate = new Date(year, month-1, day, hour, mins);
console.log(fulldate.getTime());

momentJS date string add 5 days

i have a start date string "20.03.2014" and i want to add 5 days to this with moment.js but i don't get the new date "25.03.2014" in the alert window.
here my javascript Code:
startdate = "20.03.2014";
var new_date = moment(startdate, "DD-MM-YYYY").add("DD-MM-YYYY", 5);
alert(new_date);
here my jsfiddle: http://jsfiddle.net/jbgUt/1/
How can i solve this ?
I like this string format "25.03.2014"
Hope someone can help me.
UPDATED: January 19, 2016
As of moment 2.8.4 - use .add(5, 'd') (or .add(5, 'days')) instead of .add('d', 5)
var new_date = moment(startdate, "DD-MM-YYYY").add(5, 'days');
Thanks #Bala for the information.
UPDATED: March 21, 2014
This is what you'd have to do to get that format.
Here's an updated fiddle
startdate = "20.03.2014";
var new_date = moment(startdate, "DD-MM-YYYY").add('days', 5);
var day = new_date.format('DD');
var month = new_date.format('MM');
var year = new_date.format('YYYY');
alert(day + '.' + month + '.' + year);
ORIGINAL: March 20, 2014
You're not telling it how/what unit to add. Use -
var new_date = moment(startdate, "DD-MM-YYYY").add('days', 5);
moment(moment('2015/04/09 16:00:00').add(7, 'd').format('YYYY/MM/DD HH:mm:ss'))
has to format and then convert to moment again.
The function add() returns the old date, but changes the original date :)
startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
new_date.add(5, 'days');
alert(new_date);
You can add days in different formats:
// Normal adding
moment().add(7, 'days');
// Short Hand
moment().add(7, 'd');
// Literal Object
moment().add({days:7, months:1});
See more about it on Moment.js docs: https://momentjs.com/docs/#/manipulating/add/
var end_date = moment(start_date).clone().add(5, 'days');
If we want to use the current date or present date:
var new_date = moment(moment(), "MM-DD-YYYY").add(7, 'days')
alert(new_date);
To get an actual working example going that returns what one would expect:
var startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
var thing = new_date.add(5, 'days').format('DD/MM/YYYY');
window.console.log(thing)
add https://momentjs.com/downloads/moment-with-locales.js to your html page
var todayDate = moment().format('DD-MM-YYYY');//to get today date 06/03/2018 if you want to add extra day to your current date
then
var dueDate = moment().add(15,'days').format('DD-MM-YYYY')// to add 15 days to current date..
point 2 and 3 are using in your jquery code...
If you do end up running with formatting problems after adding X time to the function, try this format:
startDate = moment(startDate).add(1, "days").format("YYYY-MM-DD");
instead of:
startDate = moment(startDate, "YYYY-MM-DD").add(1, "days");
This last version keeps the time attached to the returned data, whereas the format method doesn't and literally returns YYYY-MM-DD.
You can reduce what they said in a few lines of code:
var nowPlusOneDay = moment().add('days', 1);
var nowPlusOneDayStr = nowPlusOneDay.format('YYYY-MM-DD');
alert('nowPlusOneDay Without Format(Unix Date):'+nowPlusOneDay);
alert('nowPlusOneDay Formatted(String):'+nowPlusOneDayStr);
updated:
startdate = "20.03.2014";
var new_date = moment(startdate, "DD-MM-YYYY").add(5,'days');
alert(new_date)

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

Javascript get date in format [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I want to get today's date in the format of mm-dd-yyyy
I am using var currentDate = new Date();
document.write(currentDate);
I can't figure out how to format it.
I saw the examples var currentTime = new Date(YY, mm, dd); and currentTime.format("mm/dd/YY");
Both of which don't work
I finally got a properly formatted date using
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!`
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var today = mm+'/'+dd+'/'+yyyy;
document.write(today);'`
This seems very complex for such a simple task.
Is there a better way to get today's date in dd/mm/yyyy?
Unfortunately there is no better way, but instead of reinventing the wheel, you could use a library to deal with parsing and formatting dates: Datejs
<plug class="shameless">
Or, if you find format specifiers ugly and hard to decipher, here's a concise formatting implementation that allows you to use human-readable format specifiers (namely, the Date instance getters themselves):
date.format("{Month:2}-{Date:2}-{FullYear}"); // mm-dd-yyyy
</plug>
var today = new Date();
var strDate = 'Y-m-d'
.replace('Y', today.getFullYear())
.replace('m', today.getMonth()+1)
.replace('d', today.getDate());
Simple answer is no. Thats the only way to do it that I know of.
You can probably wrap into a function that you can reuse many times.
date.js is what you need. For example, snippet below is to convert a date to string as Java style
new Date().toString('M/d/yyyy')
function dateNow(splinter){
var set = new Date();
var getDate = set.getDate().toString();
if (getDate.length == 1){ //example if 1 change to 01
getDate = "0"+getDate;
}
var getMonth = (set.getMonth()+1).toString();
if (getMonth.length == 1){
getMonth = "0"+getMonth;
}
var getYear = set.getFullYear().toString();
var dateNow = getMonth +splinter+ getDate +splinter+ getYear; //today
return dateNow;
}
format this function is mm dd yyyy
and the dividing you can choice and replace if you want... for example
dateNow("/") you will get 12/12/2014
There is nothing built in, but consider using this if you are already using jQuery (and if not, then you should consider that as well!)
http://plugins.jquery.com/project/jquery-dateFormat
(new Date()).format("MM-dd-yyyy")
N.B. month is "MM" not "mm"
function appendZeros(value,digits){
var c= 1;
initValue = value;
for(i=0;i<digits-1;i++){
c = c*10;
if( initValue < c ){
value = '0' + value;
}
}
return value;
}

Categories