Splitting a note, preserving the date created info

I have a script that splits files at a delimiter (that I believe I pulled from this post). I am trying to modify it so that the newly created drafts keep the same createdAt value as the original. Here is what I have…

// Split at specified delimiter

var delim = "\n## ";
var tags = Draft.tags;
var date = Draft.createdAt;

var text = draft.content;
var chunks = text.split(delim);
for (var chunk of chunks) {
	var d = Draft.create();
	d.content = chunk.trim();
	d.createdAt = date;
	for (let tag of draft.tags) {
  		d.addTag(tag);
	}	
	d.update();
}

However, the date isn’t updated in the new draft. Would anyone be willing to give me a hint as to what I’m doing wrong here? Thank you in advance for any assistance you can offer.

It is not possible to set the creation date via script. That is maintained by the app. The date properties on the Draft object are readonly.

I just checked and I see the docs site does not properly reflect that, and I’ll make a note to update that to avoid confusion.

Thanks for the quick reply. Is there any way to append the date created to the end of the draft’s text?

Nevermind. I figured it out thanks to your excellent documentation. For those who are interested, here is what I am using (it places a line at the end of each newly created document with the date and time the original was created like this: created: 2020-04-24 06:36):

// Split at specified delimiter

var delim = "\n## ";
var tags = Draft.tags;
var date = draft.processTemplate("created: [[created|%Y-%m-%d %H:%M]]");

var text = draft.content;
var chunks = text.split(delim);
for (var chunk of chunks) {
	var d = Draft.create();
	d.content = chunk.trim();
	d.content = d.content + "\n" + date;
	for (let tag of draft.tags) {
  		d.addTag(tag);
	}	
	d.update();
}

This should work:

// Split at specified delimiter

let delim = "\n## ";
let date = draft.createdAt.toString("yyyy-MM-dd HH:mm");

// Make dateLine in <!-- HTML --> comment block
let dateLine = `\n\n<!-- Created: ${date} -->`

// alert(date);

let text = draft.content;
let chunks = text.split(delim);
let h2 = ''

for (const chunk of chunks) {
	let d = Draft.create();
	d.content = h2 + chunk.trim() + dateLine;
	// add stripped delim/heading tag (strip '\n') to all but first chunk:
	h2 = delim.slice(1);
	
	for (let tag of draft.tags) {
  		d.addTag(tag);
	}
	
	d.languageGrammar = draft.languageGrammar;
	d.update();
}

Oh sorry, just discovered you already had solved it. :sunglasses:
Anyway, slightly different code :nerd_face: